类ThreadPoolExecutor
最常使用的构造方法是:
ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable>workQueue
)
参数解释如下:
corePoolSize
:池中所保存的线程数,包括空闲线程,也就是核心池的大小。maximumPoolSize
:池中允许的最大线程数。keepAliveTime
:当线程数量大于corePoolSize
值时,在没有超过指定的时间内是不从线程池中将空闲线程删除的,如果超过此时间单位,则删除。unit
:keepAliveTime
参数的时间单位。workQueue
:执行前用于保持任务的队列。此队列仅保持由execute
方法提交的Runnable
任务。
其中workQueue
参数的解释对吗?我运行下面的例子发现submit
提交的Callable
任务一样会占用workQueue
,书上错了吗
public class Main {
static class MyCallable implements Callable<String> {
private int age;
public MyCallable(int age) {
super();
this.age = age;
}
public String call() throws Exception {
Thread.sleep(1000);
System.out.println("年龄是:" + age);
return "返回值 年龄是:" + age;
}
}
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(7, 8, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1));
executor.submit(new MyCallable(1));// 1
executor.submit(new MyCallable(2));// 2
executor.submit(new MyCallable(3));// 3
executor.submit(new MyCallable(4));// 4
executor.submit(new MyCallable(5));// 5
executor.submit(new MyCallable(6));// 6
executor.submit(new MyCallable(7));// 7
executor.submit(new MyCallable(8));// 8
executor.submit(new MyCallable(9));// 9
// executor.submit(new MyCallable(10));// 10
Thread.sleep(300);
System.out.println("A:" + executor.getCorePoolSize());
System.out.println("A:" + executor.getPoolSize());
System.out.println("A:" + executor.getQueue().size());
Thread.sleep(5000);
System.out.println("B:" + executor.getCorePoolSize());
System.out.println("B:" + executor.getPoolSize());
System.out.println("B:" + executor.getQueue().size());
executor.shutdown();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…