java 多线程 任务队列_Java并发编程线程池任务队列
類ThreadPoolExecutor最常使用的構造方法是:
ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueueworkQueue)
參數解釋如下:corePoolSize:池中所保存的線程數,包括空閑線程,也就是核心池的大小。
maximumPoolSize:池中允許的最大線程數。
keepAliveTime:當線程數量大于corePoolSize值時,在沒有超過指定的時間內是不從線程池中將空閑線程刪除的,如果超過此時間單位,則刪除。
unit:keepAliveTime參數的時間單位。
workQueue:執行前用于保持任務的隊列。此隊列僅保持由execute方法提交的Runnable任務。
其中workQueue參數的解釋對嗎?我運行下面的例子發現submit提交的Callable任務一樣會占用workQueue,書上錯了嗎public class Main {
static class MyCallable implements Callable {
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();
}
}
總結
以上是生活随笔為你收集整理的java 多线程 任务队列_Java并发编程线程池任务队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 软引用_Java中弱引用和软引
- 下一篇: java开闭原则 例子_解析Java编程