Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

Java并发编程线程池任务队列

ThreadPoolExecutor最常使用的构造方法是:
ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable>workQueue
参数解释如下:

  • corePoolSize:池中所保存的线程数,包括空闲线程,也就是核心池的大小。
  • maximumPoolSize:池中允许的最大线程数。
  • keepAliveTime:当线程数量大于corePoolSize值时,在没有超过指定的时间内是不从线程池中将空闲线程删除的,如果超过此时间单位,则删除。
  • unitkeepAliveTime参数的时间单位。
  • 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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不限于runnable, 如果核心线程数都在忙碌,新任务都会包装为任务加入workQueue中。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...