CallerRunsPolicy
- execute 去执行新任务,也就是main线程去执行,这种策略会降低新任务提交速度,影响整体性能。
main方法
public static void main(String[] args) {
ExecutorService es = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(3), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
MyRunnable t1 = new MyRunnable("id:1");
MyRunnable t2 = new MyRunnable("id:2");
MyRunnable t3 = new MyRunnable("id:3");
MyRunnable t4 = new MyRunnable("id:4");
MyRunnable t5 = new MyRunnable("id:5");
MyRunnable t6 = new MyRunnable("id:6");
MyRunnable t7 = new MyRunnable("id:7");
es.execute(t1);
es.execute(t2);
es.execute(t3);
es.execute(t4);
es.execute(t5);
es.execute(t6);
es.execute(t7);
}
MyRunnable类
public class MyRunnable implements Runnable {
String id;
public MyRunnable(String id) {
this.id = id;
}
@Override
public void run() {
System.out.println(id+"的线程名称:"+Thread.currentThread().getName());
}
}
控制台输出
id:6的线程名称:main
id:2的线程名称:pool-1-thread-2
id:1的线程名称:pool-1-thread-1
id:3的线程名称:pool-1-thread-2
id:7的线程名称:main
id:5的线程名称:pool-1-thread-2
id:4的线程名称:pool-1-thread-1
总结
核心线程:2;
允许存在的工作线程最大数量:2
工作队列数量:5
id6,id7执行时队列、线程都已满,此时由主线程执行。