ThreadPoolExecutor 也是一個可以擴展的線程池,它提供了beforeExecute()、afterExecute()、和terminated()3個接口對線程池進行控制。即開始執行前,執行完成後,終止後
具體擴展代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * ThreadPoolExecutor 擴展 * @author tanlk * @date 2017年7月26日下午8:47:39 */ public class MyThreadPoolExecutor extends ThreadPoolExecutor { public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override protected void beforeExecute(Thread t, Runnable r) { System.out.println( "beforeExecute MyThread Name:" + t.getName() + ",TID:" + t.getId()); } @Override protected void afterExecute(Runnable r, Throwable t) { System.out.println( "afterExecute TID:" + Thread.currentThread().getId()); System.out.println( "afterExecute PoolSize:" + this .getPoolSize()); } @Override protected void terminated() { System.out.println( "terminated" ); } public static void main(String[] args) { MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); for (int i = 0; i < 10; i++) { myThreadPoolExecutor.submit( new Runnable() { public void run() { try { TimeUnit.SECONDS.sleep(1); System.out.println( "執行完" ); } catch (InterruptedException e) { e.printStackTrace(); } } }); } //myThreadPoolExecutor.shutdownNow(); } } |
通過擴展線程池,開發者可以獲取線程池調度的內部細節,對並行程序故障排查很有幫助