Executors.newCachedThreadPool(): 创建一个可缓存线程池,该线程池根据需要创建新线程,但会重用先前构建的可用线程。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
executor.execute(new Task());
}
executor.shutdown();
}
static class Task implements Runnable {
public void run() {
System.out.println("Executing task with thread: " + Thread.currentThread().getName());
}
}
}
Task类实现了Runnable接口,并被提交给CachedThreadPool执行。线程池会根据需要创建新线程,如果线程空闲60秒,则会终止。