美文网首页
RejectThreadPoolDemo

RejectThreadPoolDemo

作者: a8df7b7f7cf3 | 来源:发表于2018-12-24 00:22 被阅读0次
package com.zxz.pgdemo.controller;

import java.util.concurrent.*;

public class RejectHandlerDemo {
    public static class MyTask implements Runnable {
        public Object data;
        public CountDownLatch countDownLatch;
        public MyTask(Object data, CountDownLatch countDownLatch) {
            this.data=data;
            this.countDownLatch=countDownLatch;
        }

        @Override
        public void run() {
            doWork(data);
            countDownLatch.countDown();
        }

        public void doWork(Object data) {
            System.out.println(System.currentTimeMillis() + ":Thread ID:" + Thread.currentThread().getId() + ";data=" + data.toString());
        }
    }


    public static void main(String args[]) throws InterruptedException {

        LinkedBlockingDeque<Runnable> queue = new LinkedBlockingDeque<>(10);
        ExecutorService executorService = new ThreadPoolExecutor(5, 5,
                0L, TimeUnit.SECONDS,
                queue,
                Executors.defaultThreadFactory()
                , (r, executor) -> {
                    try {
                        queue.put(r);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println(r.toString() + " is discard");
                    }

                });

        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            executorService.submit(new MyTask(i, countDownLatch));
            Thread.sleep(10);
        }
        countDownLatch.await();
        System.out.println("---------done--------");
        executorService.shutdown();
    }
}

网友评论

      本文标题:RejectThreadPoolDemo

      本文链接:https://www.haomeiwen.com/subject/qczokqtx.html