java 線程池
Java 的 concurrent
包下提供了多種線程池的實現,使用起來非常方便
ExecutorService
ExecutorService
是線程池的抽象接口,concurrent
包提供了如下如下幾個線程池的實現
-
Executors.newSingleThreadExecutor
: 僅由一個線程組成的線程池 -
Executors.newFixedThreadPool(num)
: 固定線程數量的線程池 -
Executors.newCachedThreadPool
: 按需創建新的線程,用完的線程放入線程池重復使用,空閑的線程會在 60s 后釋放 -
Executors.newWorkStealingPool()
: 工作竊取線程池,內部有固定數量(cpu 核數)的線程,如果當前線程的任務完成,會竊取其他線程的任務,其實就是ForkJoinPool
-
Executors.newSingleThreadScheduledExecutor
: 支持延遲執行的單個線程池 -
Executors.newScheduledThreadPool(num)
: 支持延遲執行的固定數量的線程池
ExecutorService
主要提供如下幾個接口
-
execute(runnable)
: 將一個 runnable 任務放到線程池中執行 -
submit(callable)
: 提交一個 callable 任務,返回一個 future 對象,可以獲取 callable 的返回值 -
invokeAll
: 提交集合中所有的 callable -
shutdown
: 關閉線程池,等待當前所有線程的完成正在執行的任務,執行完成后,線程退出,這個函數只是發出退出信號,并不會阻塞等待線程退出 -
awaitTermination
: 等待所有線程退出,需要提前掉用shutdown
ExecutorService es1 = Executors.newSingleThreadExecutor();
ExecutorService es2 = Executors.newFixedThreadPool(4);
ExecutorService es3 = Executors.newCachedThreadPool();
ExecutorService es4 = Executors.newWorkStealingPool();
ScheduledExecutorService es5 = Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService es6 = Executors.newScheduledThreadPool(4);
execute
執行一個沒有返回值的任務
ExecutorService es = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
// execute 執行一個沒有返回值的任務
es.execute(() -> System.out.println("hello world"));
}
try {
es.shutdown();
while (!es.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
// nothing to do
}
} catch (Exception e) {
e.printStackTrace();
}
submit
提交一個有返回值的任務
class Power implements Callable<Integer> {
private final int i;
private Power(int i) {
this.i = i;
}
@Override
public Integer call() throws Exception {
return i * i;
}
}
ExecutorService es = Executors.newCachedThreadPool();
List<Future<Integer>> res = Lists.newArrayListWithCapacity(10);
for (int i = 0; i < 10; i++) {
// submit 提交一個有返回值的任務,通過 Future 對象獲取返回值
res.add(es.submit(new Power(i)));
}
for (int i = 0; i < 10; i++) {
try {
Future<Integer> future = res.get(i); // 阻塞等待任務完成
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
try {
es.shutdown();
while (!es.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
// nothing to do
}
} catch (Exception e) {
e.printStackTrace();
}
ScheduledExecutor
延遲執行的線程池,提供一個新的接口
-
schedule
: 延遲執行任務
ScheduledExecutorService es = Executors.newScheduledThreadPool(4);
for (int i = 0; i < 10; i++) {
es.schedule(() -> System.out.println("hello world"), i, TimeUnit.SECONDS);
}
for (int i = 0; i < 10; i++) {
es.schedule(() -> {
int sum = 0;
for (int j = 0; j < 10; j++) {
sum += j;
}
return sum;
}, i, TimeUnit.SECONDS);
}
try {
es.shutdown();
while (!es.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
// nothing to do
}
} catch (Exception e) {
e.printStackTrace();
}