ThreadPoolExecutor扩展


import java.util.concurrent.*;

/**
 * ThreadPoolExecutor扩展
 */
public class ExtThreadPool {
    public static class MyTask implements Runnable{
        public String name;

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("正在执行 Id:"+Thread.currentThread().getId()+",Name:"+Thread.currentThread().getName());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException{
        ExecutorService executor = new ThreadPoolExecutor(5, 5, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()){
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
               System.out.println("准备执行:"+((MyTask)r).name);
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("执行完成:"+((MyTask)r).name);
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
            }
        };
        for (int i = 0; i < 5; i++) {
            MyTask task = new MyTask("TASK-"+i);
            executor.execute(task);
            Thread.sleep(10);
        }
        executor.shutdown();//关闭线程池,它会等待所有任务执行完成后,再关闭线程池
    }
    //准备执行:TASK-0
    //正在执行 Id:9,Name:pool-1-thread-1
    //准备执行:TASK-1
    //正在执行 Id:10,Name:pool-1-thread-2
    //准备执行:TASK-2
    //正在执行 Id:11,Name:pool-1-thread-3
    //准备执行:TASK-3
    //正在执行 Id:12,Name:pool-1-thread-4
    //准备执行:TASK-4
    //正在执行 Id:13,Name:pool-1-thread-5
    //执行完成:TASK-0
    //执行完成:TASK-1
    //执行完成:TASK-2
    //执行完成:TASK-3
    //执行完成:TASK-4
    //线程池退出
}
posted @ 2019-09-05 10:04  fly_bk  阅读(203)  评论(0编辑  收藏  举报