线程池中的提交优先级和执行优先级

public class ThreadPoolApp { 
	public static void main(String[] args) throws Exception { 
        ExecutorService executorService = new ThreadPoolExecutor(
                3, 6, 0, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                new CustomizableThreadFactory("TK-")
        );

        for (int i = 1; i <= 10; i++) { 
            final int index = i;
            TimeUnit.MILLISECONDS.sleep(10);
            executorService.execute(() -> { 
                try { 
                    System.out.println(
                            String.format("%s Thread %s, index %d.",
                                    LocalDateTime.now().format(
                                            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                                    ),
                                    Thread.currentThread().getName(), index)
                    );
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) { 
                    e.printStackTrace();
                }
            });
        }
    }
}
2021-03-05 13:56:10 Thread TK-2, index 2.
2021-03-05 13:56:10 Thread TK-3, index 3.
2021-03-05 13:56:10 Thread TK-1, index 1.			// TK-1~TK-3为核心线程任务
2021-03-05 13:56:10 Thread TK-4, index 7.
2021-03-05 13:56:10 Thread TK-5, index 8.
2021-03-05 13:56:10 Thread TK-6, index 9.			// TK-7~TK-9为非核心线程任务 
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.jaemon.demo.ThreadPoolApp$$Lambda$1/1780132728@52f759d7 rejected from java.util.concurrent.ThreadPoolExecutor@7cbd213e[Running, pool size = 6, active threads = 6, queued tasks = 3, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.jaemon.demo.ThreadPoolApp.main(ThreadPoolApp.java:137)	
2021-03-05 13:56:15 Thread TK-2, index 4.
2021-03-05 13:56:15 Thread TK-1, index 5.
2021-03-05 13:56:15 Thread TK-3, index 6.			// TK-4~TK-6为工作队列中任务

提交优先级: 核心线程 > 工作队列 > 非核心线程
执行优先级: 核心线程 > 非核心线程 > 工作队列

    原文作者:Jaemon
    原文地址: https://blog.csdn.net/u010979642/article/details/114393660
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞