自定義線程池,有界隊列,任務被拒絕後的自定義操做

public class CustomThreadPool {
    //自定義拒絕策略
    private static class myReject implements RejectedExecutionHandler{
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println("當前被拒絕任務爲:" + r.toString());
        }
    }
    //自定義等待隊列
    private static LinkedBlockingDeque<Runnable> blockingQueue=new LinkedBlockingDeque<>(1);
    //自定義線程建立工廠
    private static ThreadFactory factory=new ThreadFactory() {
        AtomicInteger atomicInteger=new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            Thread thread=new Thread(r);
            //thread.setName("testThread"+atomicInteger.getAndIncrement());
            return thread;
        }
    };
    //自定義線程池建立者
    private static ThreadPoolExecutor pool=new ThreadPoolExecutor(3,
            3,
            10,
            TimeUnit.SECONDS,blockingQueue,factory,new myReject());
    //任務
    private static class task implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"執行");
        }
    }
    public static void main(String[] args) {
        //建立六個任務
        for (int i=0;i<6;i++){
            pool.execute(new task());
        }
    }
}

結果如圖:併發

 

https://blog.csdn.net/qiushisoftware/article/details/79155059ide

案例 :編寫代碼同時只容許五個線程併發訪問(信號量、自定義線程池等實現方式):https://www.jianshu.com/p/d7d41e1ae40datom

相關文章
相關標籤/搜索