线程池的学习之ThreadPoolExecutor的测试

各个字段的解释以及测试用例

public class Test {

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,//核心线程数
                4,//最大线程数
                1,//空闲线程时间(当有线程的空闲时间超过此设置,则会销毁,直到线程数等于核心线程数)
                TimeUnit.MINUTES,//上个字段的单位
                new LinkedBlockingQueue<>(3),//当线程过多,最大线程也不够时,放入队列
                new DefaultThreadFactory("gzy"),//线程工厂,可以给线程池命名
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println("rejectedExecution:" + ":" + executor.toString());
                    }
                }//当线程数目多到队列也装不下时,拒绝策略
				);
        for (int i = 0; i < 9; i++) {
            Object o = new Integer(i);
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(((Integer) o).toString() + "---------" + Thread.currentThread());
                }
            });
        }
    }
}

执行结果,很明显,只输出了7(最大线程4+队列3)条正常数据,其余执行了拒绝的输出

rejectedExecution::java.util.concurrent.ThreadPoolExecutor@3764951d[Running, pool size = 4, active threads = 4, queued tasks = 3, completed tasks = 0]
rejectedExecution::java.util.concurrent.ThreadPoolExecutor@3764951d[Running, pool size = 4, active threads = 4, queued tasks = 3, completed tasks = 0]
5---------Thread[gzy-1-3,5,main]
6---------Thread[gzy-1-4,5,main]
1---------Thread[gzy-1-2,5,main]
0---------Thread[gzy-1-1,5,main]
2---------Thread[gzy-1-3,5,main]
3---------Thread[gzy-1-4,5,main]
4---------Thread[gzy-1-2,5,main]
发布了148 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33321609/article/details/104472935