1 package com.thread.test.thread;
2
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.LinkedBlockingQueue;
5 import java.util.concurrent.RejectedExecutionHandler;
6 import java.util.concurrent.ThreadLocalRandom;
7 import java.util.concurrent.ThreadPoolExecutor;
8 import java.util.concurrent.TimeUnit;
9
10 /**
11 * ThreadPoolExecutor
12 * 通過線程池執行所提交的任務的ExecutorService,通常由Executors生成
13 * 執行高並發任務比較高效,因為減少了任務的穿行等待時間,同時很好的管理著執行需求的資源,包括線程,
14 * 通常,維護者一些基礎的任務執行數據,例如已完成任務數量
15 *
16 * ThreadPoolExecutor有許多可調正的參數,可以適用於不同的用途,但是通常我們使用
17 * Executors#newCachedThreadPool 無容量限制,線程自動回收
18 * Executors#newFixedThreadPool 固定容量線程池
19 * Executors#newSingleThreadExecutor 單線程
20 * 等為許多通用場景預置了很多參數,
21 *
22 * Hello world!
23 *
24 */
25 public class ThreadPoolFactoryTest
26 {
27 public static void main( String[] args )
28 {
29 /**
30 * @ int corePoolSize:線程池中維護的線程數量,生命周期同線程池,除非設置了allowCoreThreadTimeOut
31 * @ int maximumPoolSize:允許的最大數量
32 * @ long keepAliveTime:允許的最大存活時間
33 * @ TimeUnit unit:單位
34 * @ BlockingQueue<Runnable> workQueue:存儲等待執行任務,execute提交的Runnable類型任務
35 * @ RejectedExecutionHandler handler:線程阻塞,隊列已滿時執行的操作
36 */
37 ExecutorService enew = new ThreadPoolExecutor(5, 20, 0L,
38 TimeUnit.SECONDS,
39 new LinkedBlockingQueue<Runnable>(),
40 new RejectedExecutionHandler() {
41 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
42 System.out.println("this is the exception execution begin");
43 executor.execute(r);
44 System.out.println("this is the exception execution end");
45 }
46 });
47
48 for (int i = 0; i < 100; i++) {
49 enew.execute(new Runnable() {
50 public void run() {
51 int l = ThreadLocalRandom.current().nextInt();
52 System.out.println("task..." + l + "begin");
53 try {
54 Thread.sleep(2000);
55 System.out.println("task..." + l + "end");
56 } catch (InterruptedException e) {
57 e.printStackTrace();
58 }
59 }
60 });
61 }
62 System.out.println("add end...");
63 }
64 }
項目地址:https://github.com/windwant/threadtest