ThreadPoolExecutor 扩展

来源:互联网 发布:淘宝卖保健品填厂家 编辑:程序博客网 时间:2024/06/01 22:16
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();
    }
 
}

通过扩展线程池,开发者可以获取线程池调度的内部细节,对并行程序故障排查很有帮助