版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
常用三种线程池
newFixedThreadPool
定义一个定长线程池,可控制最大线程并发数,超过的线程会在队列中等待
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i <5 ; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"处理业务");
});
}
}
}
输出
pool-1-thread-1处理业务
pool-1-thread-2处理业务
pool-1-thread-3处理业务
pool-1-thread-4处理业务
pool-1-thread-5处理业务
内部实现
corecorePoolSize和maximumPoolSize值是相等的,它使用的是LinkedBlockingQueue
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newSingleThreadPool
创建一个单线程化的线程池,它之会用唯一的工作线程来执行任务,保证所有任务按照顺序执行
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i <5 ; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"处理业务");
});
}
}
}
输出
pool-1-thread-1处理业务
pool-1-thread-1处理业务
pool-1-thread-1处理业务
pool-1-thread-1处理业务
pool-1-thread-1处理业务
内部实现
corecorePoolSize和maximumPoolSize值都设置为1,它使用的是LinkedBlockingQueue
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newCachedThreadPool
创建一个可缓存线程池,如果线程长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i <5 ; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"处理业务");
});
}
}
}
输出
pool-1-thread-1处理业务
pool-1-thread-2处理业务
pool-1-thread-3处理业务
pool-1-thread-4处理业务
pool-1-thread-5处理业务
另一个示例
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i <5 ; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"处理业务");
});
try {
TimeUnit.SECONDS.sleep(2);//设置一个线程可以延缓的时间,以展示按照任务数量而调度的线程机制
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
输出
pool-1-thread-1处理业务
pool-1-thread-1处理业务
pool-1-thread-1处理业务
pool-1-thread-1处理业务
pool-1-thread-1处理业务
内部实现
corecorePoolSize设置为0,maximumPoolSize设置为Integer.MAX_VALUE,它使用的是SynchronousQueue
来了任务就创建线程,当线程空闲超过60秒,就销毁线程。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}