Java并发编程线程池任务队列
类
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();
}
}
回答
submit方法写的明明白白,最终通过你的callable创建一个
通过excute方法执行。。。。也就是说callable也是通过excute执行的
以上是 Java并发编程线程池任务队列 的全部内容, 来源链接: utcz.com/a/41636.html