JDK并发包线程池(三)自定义线程池

自定义线程池就是自己创建ThreadPoolExecutor对象,根据自己的需求指定里面的各个参数
自定义线程池的拒绝策略,需要实现RejectedExecutionHandler接口
自定义线程的创建工厂ThreadFactory,ThreadFactory是一个工厂,自定义ThreadFactory可以跟踪线程池在某个时刻创建了多少个线程,也可以自定义线程的名称,组以及优先级等信息

public class MyThreadExecutorPool {
    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10),new ThreadFactory() {

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                //将线程设置成为守护线程,这样当主线程退出的时候,线程池就会被销毁了,因为守护线程就是用来为主线程服务的,主线程退出了,守护线程当然退出
                //thread.setDaemon(true);
                System.out.println("线程创建完毕"+Thread.currentThread().getId());
                return thread;
            }
        },new RejectedExecutionHandler() {

            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                //DiscardPolicy过于简单,直接就默默地抛弃了不能执行的任务,这里我们可以打印出一些信息
                System.out.println(r.toString()+"isDiscard");
            }
        });

        for(int i=0;i<20;i++){
            poolExecutor.submit(new MyTask(i));
        }
    }
}

class MTask implements Runnable{
    private int i;

    public MTask(int i) {
        super();
        this.i = i;
    }

    @Override
    public void run() {
        System.out.println(new Date().getTime()+"___"+Thread.currentThread().getId()+"___"+i);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

上面程序的运行可能结果:

线程创建完毕1                                         //证明这个方法的调用是由主线程完成的
线程创建完毕1
线程创建完毕1
线程创建完毕1
线程创建完毕1
//因为corePoolSize=maxmiumPoolSize,并且任务队列是有界队列,当新的任务提交后发现队列满了,线程的数量也达到maxmium,然后就会拒绝执行
java.util.concurrent.FutureTask@3fd97efcisDiscard   
java.util.concurrent.FutureTask@69dfe453isDiscard
java.util.concurrent.FutureTask@6a073b72isDiscard
java.util.concurrent.FutureTask@cfefc0isDiscard
java.util.concurrent.FutureTask@19501026isDiscard
1497184497324___10___1
1497184497324___11___2
1497184497324___12___3
1497184497324___13___4
1497184497324___9___0
1497184498324___13___5
1497184498324___10___6
1497184498325___11___7
1497184498326___12___8
1497184498326___9___9
1497184499325___13___10
1497184499325___10___11
1497184499325___11___12
1497184499326___12___13
1497184499326___9___14

你可能感兴趣的:(线程,并发,线程池,自定义,拒绝策略)