ExecutorService exe = Executors.newFixedThreadPool(4);
ThreadPoolExecutor(4,4,0L, TimeUnit.MILLSECONDS, new LinkedBlockingQueue<Runnable>());
结果:
1. 当开始运行时,线程池中的线程小于corePoolSize时,开启新的线程;
2. 当新的任务添加,线程池线程超过corePoolSize时,任务放在队列中;
3. 实际运行的线程最大不超过maximumPoolSize,即4;
4. queueSize=getTaskCount-getCompletedTaskCount-getActiveCount;
5. 提交的任务不一定是按提交顺序完成运行,如提交顺序是id_1,id_2,id_3,id_4,可能id_4最先完成执行。
ExecutorService exe = Executors.newCachedThreadPool();
ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
结果:
1. 当新的任务添加,线程池中无空闲线程时,创建新的线程,否则使用空闲线程执行该任务;
2. queueSize一直为0,空闲线程的数量=getLargestPoolSize-getAcitveCount(超时之前);
3. getTaskCount=getActiveCount+getCompletedTaskCount;
4. 线程依然不是严格按提交顺序完成;
ExecutorService exe = Executors.newSingleThreadExecutor();
FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L,TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
结果:
1. 当新任务添加时,创建新线程执行任务,且线程数不能超过1;
2. 新任务提交时,上一个任务正在执行,则加入到队列中;
3. 任务都是严格按提交顺序执行;
ThreadPoolExecutor exe = new ThreadPoolExecutor(4,10,0,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
结果:
1. 当添加新任务,且线程池线程数少于corePoolSize,启动新线程执行任务;
2. 当添加新任务,且线程池线程大于corePoolSize,将任务添加到队列中;
3. 当添加新任务,且任务队列已满,且线程数少于maximumPoolSize,启动新线程;
4. 当添加新任务,且任务队列已满,线程池线程数大于maximumPoolSize,执行拒绝策略;
5. 异常抛出时,getLargestPoolSize==getMaximumPoolSize;
6. 异常抛出后,执行中的任务和队列中的任务依然被提交执行;
7. getTaskCount=getCompletedTaskCount+getActiveCount+getQueueSize;
8. 任务非严格按提交顺序执行,且乱序的情况比之前更严重;
ThreadPoolExecutor exe = new ThreadPoolExecutor(4,10,0,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(10), Executors.defaultThreadFactory(), new DiscardPolicy());
结果:
1. 队列满,且线程数超过maximumPoolSize后,新来的任务被抛弃;
2. 最终执行完成的线程数与任务提交的频率和执行的效率有关;
ThreadPoolExecutor exe = new ThreadPoolExecutor(4,10,0,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),Executors.defaultThreadFactory(), new DiscardOldestPolicy());
1000个任务,每个线程sleep(50);
结果:
1. 队列满,且线程数超过maximumPoolSize后,队列中最老的任务被抛弃;
2. 最终执行完成的线程数与任务提交的频率和执行的效率有关;
ThreadPoolExecutor exe = new ThreadPoolExecutor(4,10,0,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),Executors.defaultThreadFactory(), new CallerRunsPolicy());
结果:
1. 90%以上的任务被执行,只有少数没有被执行;
2. 当队列长度为1,10,50,100,500时,线程执行的总时间与队列大小成反比,与完成总数成正比;
(时间和完成任务数,各五次);
//1000: 12564 1000 12574 1000
//500: 4873 956 4873 956 4873 956 4889 956 4873 956
//100: 4682 921 4671 921 4636 920 4674 921 4634 920
//50: 4627 916 4632 916 4629 917 4629 917 4626 917
//10: 4618 912 4623 913 4622 913 4627 913 4621 913
//1: 4839 910 4829 910 4838 910 4827 910 4902 910
来源:oschina
链接:https://my.oschina.net/u/1269609/blog/227355