//Executors 工具类,三大方法
public class Demo01 {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程池
//ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定的线程池大小:5个
ExecutorService threadPool = Executors.newCachedThreadPool();//缓存,可伸缩的池
try {
for (int i = 0; i < 10; i++) {
//使用线程池创建线程
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+" OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//线程池用完需关闭
threadPool.shutdown();
}
}
}
Executors 工具类,三大方法
最新推荐文章于 2024-11-11 21:31:22 发布
本文介绍了Java中的ExecutorService工具类,展示了如何创建单线程池、固定大小线程池以及可缓存的线程池。通过示例代码解释了如何使用ExecutorService执行任务,并强调了线程池使用完毕后必须关闭的重要性。
1196

被折叠的 条评论
为什么被折叠?



