Created
September 20, 2020 19:37
-
-
Save sne007/f37b2dec46c855ed689d7497d4e6757b to your computer and use it in GitHub Desktop.
ExecutorService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.ForkJoinPool; | |
public class Main { | |
public static void main(String[] args) { | |
ExecutorService s = Executors.newFixedThreadPool(2); | |
// System.out.println(Runtime.getRuntime().availableProcessors()); | |
// ForkJoinPool fk = (ForkJoinPool) Executors.newWorkStealingPool(); | |
Runnable task1 = () -> { | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println(Thread.currentThread().getName()); | |
}; | |
Runnable task2 = () -> { | |
try { | |
Thread.sleep(2000); | |
System.out.println(Thread.currentThread().getName()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
Runnable task3 = () -> { | |
try { | |
Thread.sleep(2000); | |
System.out.println(Thread.currentThread().getName()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
Runnable task4 = () -> { | |
try { | |
Thread.sleep(2000); | |
System.out.println(Thread.currentThread().getName()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
CompletableFuture c = CompletableFuture.runAsync(task1, s); | |
s.submit(task2); | |
s.submit(task3); | |
try { | |
if (c.isDone()) { | |
System.out.println(c.get()); | |
} | |
} catch (InterruptedException | ExecutionException e) { | |
e.printStackTrace(); | |
} | |
System.out.println(fact(29)); | |
Long startTime = System.currentTimeMillis(); | |
/* | |
fk.submit(() -> { | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}); | |
fk.submit(() -> System.out.println(fact(29))); | |
*/ | |
Long endTime = System.currentTimeMillis(); | |
// System.out.println((endTime - startTime) / 1000); | |
} | |
public static int fact(int n) { | |
if (n == 0 || n == 1) { | |
return 1; | |
} | |
return n * fact(n - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment