【JUC并发】自定义线程池:超时版(工作线程获取任务超时)。ReentrantLock,Condition(awaitNanos),synchronized,timeUnit

普通版:自定义线程池——普通版
拒绝策略版(生产者添加任务到阻塞队列失败) :自定义线程池——拒绝策略版

实现逻辑

在这里插入图片描述

实现

ThreadPool2

/**
 * 自定义线程池-线程获取任务超时版:线程获取任务超时返回null,在线程集合中移除该线程
 */
@Slf4j(topic = "c.eight-Demo2")
class ThreadPool2{
    //线程集合:用来存放工作线程
    private HashSet<Wroking> threadsSet;
    //集合最大值:用户指定线程池的线程数量
    private final int threadsSetSize;
    //阻塞队列:工作线程繁忙时存放任务
    private BlockingQueue2<Runnable> blockingQueue;
    //获取任务超时时间
    private long timeout;
    //时间单位
    private TimeUnit timeUnit;

    ThreadPool2(int threadsSetSize,int blockingQueueSize,long timeout,TimeUnit timeUnit) {
        threadsSet=new HashSet<>();
        this.threadsSetSize=threadsSetSize;
        blockingQueue=new BlockingQueue2(blockingQueueSize);
        this.timeout=timeout;
        this.timeUnit=timeUnit;
    }
    //1.调用线程池的execute(Runnable r)
    public synchronized void execute(Runnable r){
        //2.判断线程集合的大小是否>=最大线程数?
        if(threadsSet.size()>=threadsSetSize){
            //2.2 是,将任务添加到阻塞队列中
            blockingQueue.put(r);
        }else {
            //   2.1 否,创建Worker对象并添加到线程集合中并启动线程.Worker对象继承Thread
            Wroking wroking=new Wroking(r);
            threadsSet.add(wroking);
            wroking.start();
        }
    }
    //自定义工作线程
    class Wroking extends Thread{
        //该线程执行的任务内容
        Runnable task;
        public Wroking(Runnable r) {
            task=r;
        }
        @Override
        public void run() {
            //在run()中执行Runnable任务,执行完成后从阻塞队列中获取任务继续执行
            while(task!=null || (task=blockingQueue.get(timeout,timeUnit))!=null){
                task.run();
                task=null;
            }
            //任务全部执行完毕,在线程集合中移除线程。
            threadsSet.remove(this);
            log.debug("移除线程"+this);
        }
    }
}

BlockingQueue2

/**
 * 自定义阻塞队列
 */
@Slf4j(topic = "c.eight-Demo2")
class BlockingQueue2<T>{
    //任务队列
    private Deque<T> tasksQueue=new ArrayDeque<>();
    //队列最大值
    private int blockingQueueSize;
    //锁
    private ReentrantLock lock=new ReentrantLock();
    //消费者条件变量
    private Condition Consumer=lock.newCondition();
    //生产者条件变量
    private Condition Producer=lock.newCondition();

    public BlockingQueue2(int blockingQueueSize) {
        this.blockingQueueSize=blockingQueueSize;
    }

    //将任务添加到阻塞队列中
    public void put(T r) {
        lock.lock();
        try{
            //        3.阻塞队列判断队列大小是否==限制大小
            while(tasksQueue.size()==blockingQueueSize){
                //        3.2 是,将执行任务的线程阻塞在生产者的条件变量中
                try {
                    Producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            //        3.1 否,将任务添加到队列队尾并唤醒消费者条件变量中的阻塞线程
            tasksQueue.addLast(r);
            Consumer.signal();
        }finally {
            lock.unlock();
        }
    }
    //线程任务执行完毕,取任务
    public T get(long timeout, TimeUnit timeUnit) {
        lock.lock();
        //获取不到任务需要等待的时间
        long need = timeUnit.toNanos(timeout);
        try{
            while(tasksQueue.size()==0){
                //       2.1.1 队列为空,进入消费者条件变量中进行阻塞
                if (need>0){
                    try {
                        //等待被唤醒后获得剩余等待时间。
                        need=Consumer.awaitNanos(need);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    return null;
                }
            }
            //       2.1.2 队列不为空,获取任务执行并唤醒生产条件变量中的生产线程
            T r=tasksQueue.pollFirst();
            Producer.signal();
            return r;
        }finally {
            lock.unlock();
        }
    }
}

测试

代码

public static void main(String[] args) {
        ThreadPool2 threadPool=new ThreadPool2(2,1,3000,TimeUnit.NANOSECONDS);
        for (int i = 0; i < 5; i++) {
            int j=i;
            threadPool.execute(()->{
                log.debug("执行任务"+j);
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("任务"+j+"执行完毕");

            });
        }
    }

结果

18:20:46 [Thread-1] c.eight-Demo2 - 执行任务1
18:20:46 [Thread-0] c.eight-Demo2 - 执行任务0
18:20:48 [Thread-1] c.eight-Demo2 - 任务1执行完毕
18:20:48 [Thread-0] c.eight-Demo2 - 任务0执行完毕
18:20:48 [Thread-1] c.eight-Demo2 - 执行任务2
18:20:48 [Thread-0] c.eight-Demo2 - 执行任务3
18:20:50 [Thread-1] c.eight-Demo2 - 任务2执行完毕
18:20:50 [Thread-1] c.eight-Demo2 - 执行任务4
18:20:50 [Thread-0] c.eight-Demo2 - 任务3执行完毕
18:20:52 [Thread-1] c.eight-Demo2 - 任务4执行完毕
18:20:53 [Thread-0] c.eight-Demo2 - 移除线程Thread[Thread-0,5,main]
18:20:55 [Thread-1] c.eight-Demo2 - 移除线程Thread[Thread-1,5,main]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿你满腹经纶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值