可緩存線程池newCachedThreadPool定義:
一個可根據需要創建新線程的線程池,如果現有線程沒有可用的,則創建一個新線程並添加到池中,如果有被使用完但是還沒銷燬的線程,就複用該線程。終止並從緩存中移除那些已有 60 秒鐘未被使用的線程。因此,長時間保持空閒的線程池不會使用任何資源。
這種線程池比較靈活,對於執行很多短期異步任務的程序而言,這些線程池通常可提高程序性能。
實例一:複用性
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newCachedThreadPool();
System.out.println(service);
for (int i = 0; i < 20; i++) {
service.execute(() -> {
System.out.println(Thread.currentThread().getName());
});
}
System.out.println(service);
service.shutdown();
}
通過輸出可以看到有些線程執行完任務後,會空閒下來,有新的任務提交時,會利用空閒線程執行。
實例二:60秒銷燬
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newCachedThreadPool();
System.out.println(service);
for (int i = 0; i < 2; i++) {
service.execute(() -> {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
});
}
System.out.println(service);
TimeUnit.SECONDS.sleep(70);
System.out.println(service);
}
在控制檯我們看到,輸出的service對象裏有一個屬性pool size,他指的是線程池裏的線程數,當過了60秒仍然沒有任務來使用線程時,線程會自動釋放。