Spring线程池任务执行顺序测试

package threadtest;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolTest {

    static class Worker extends Thread {
        private String name;

        public Worker() {
        }

        public Worker(String name) {
            super(name);
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("This is thread:" + name + " begin");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("This is thread:" + name + " end");
        }
    }

    public static void main(String[] args) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setQueueCapacity(48);
        executor.setMaxPoolSize(2);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();

        for (int i=1; i<=50; i++) {
            executor.submit(new Worker("w" + i));
        }
        System.out.println(executor.getPoolSize());
    }

}

这里我们通过代码的方式新建一个线程池,然后CorePoolSize只设置1,然后设置了48大小的等待队列,最后将MaxPoolSize设置为2.

我们的Worker线程需要10秒钟才能执行完毕,所以理论上应该同时执行Worker-1和Worker-50,而Woker-2到Worker-49都在队列里等待。

运行结果如下,印证了我们的猜想。

 

posted @ 2021-12-19 16:30  XIAOSHUA  阅读(199)  评论(0编辑  收藏  举报