线程池扩展功能使用示例

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://junmoxiao.blog.csdn.net/article/details/98972078

使用了beforeExecute()、afterExecute()、terminated()方法。
作用:

  • beforeExecute():在每个任务执行前执行。
  • afterExecute():在每个任务执行后执行。
  • terminated():在线程池关闭后执行。
import java.util.Random;
import java.util.concurrent.*;

public class ThreadPoolExt {
    static class Worker implements Runnable{
        private String taskName;
        private Random r = new Random();

        public Worker(String taskName){
            this.taskName = taskName;
        }

        public String getName() {
            return taskName;
        }

        @Override
        public void run(){
            System.out.println(Thread.currentThread().getName()
            		+" process the task : " + taskName);
            try {
                Thread.sleep(r.nextInt(1000)*5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args){
        ExecutorService threadPool = new ThreadPoolExecutor(2, 4, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
                new ThreadPoolExecutor.DiscardOldestPolicy()){
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println("Ready Execute "+((Worker)r).getName());
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("Complete Execute "+((Worker)r).getName());
            }

            @Override
            protected void terminated() {
                System.out.println("terminated ");
            }
        };

        for (int i = 0; i <3; i++){
            Worker worker = new Worker("worker " + i);
            System.out.println("A new task has been added : " + worker.getName());
            threadPool.execute(worker);
        }
        threadPool.shutdown();

    }
}

结果:
在这里插入图片描述
可以看到,结果符合预期。
任务1,0启动后没有立马启动任务2,你知道为什么吗?

参考:Mark—笔记_Java并发编程

没有更多推荐了,返回首页