JUC多线程学习

文章展示了如何创建一个自定义线程池,包括核心线程数、超时设置和时间单位。线程池使用了一个阻塞队列来存储任务,当队列满时,执行put操作会等待。同时,文章中还定义了一个Worker类,负责从队列中取出并执行任务。日志记录使用了Slf4j进行调试信息输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Slf4j(topic = "c.Test")
public class Test {
    public static void main(String[] args) {
        ThreadPool threadPool=new ThreadPool(10,2,1000,TimeUnit.MILLISECONDS);
        for (int i=0;i<5;i++){
            int j=i;
            threadPool.execute(()->{
                log.debug("{}",j);
            });
        }
    }
}
@FunctionalInterface
interface RejectPolicy<T> {
    void reject(BlockingQueue<T> queue, T task);
}
@Slf4j(topic = "c.ThreadPool")
class ThreadPool{
    private BlockingQueue<Runnable> taskQueue;
    private HashSet<Worker> workers=new HashSet<>();
    private int coreSize;
    private long timeout;
    private TimeUnit unit;

    public void execute(Runnable task){
        synchronized (workers){
            if (workers.size()<coreSize){
                Worker worker=new Worker(task);
                workers.add(worker);
                log.debug("新增worker对象");
                worker.start();
            }else {
                taskQueue.put(task);
            }
        }
    }

    public ThreadPool(int queueCapcity, int coreSize, long timeout, TimeUnit unit) {
        this.taskQueue = new BlockingQueue<>(queueCapcity);
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.unit = unit;
    }
    class Worker extends Thread{
        private Runnable task;
        public Worker(Runnable task) {
            this.task=task;
        }

        @Override
        public void run() {
            while (task!=null||(task=taskQueue.take())!=null){
                try {
                    task.run();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    task=null;
                }
            }
            synchronized (workers){
                log.debug("worker被移除{}",this);
                workers.remove(this);

            }
        }
    }
}
class BlockingQueue<T> {
    private Deque<T> queue=new ArrayDeque<>();
    private ReentrantLock lock=new ReentrantLock();
    private Condition fullWaitSet=lock.newCondition();
    private Condition emptyWaitSet=lock.newCondition();
    //    容量
    private int capcity;

    public BlockingQueue(int capcity) {
        this.capcity = capcity;
    }

    public T poll(long timeout, TimeUnit unit){
        lock.lock();
        long nanos= unit.toNanos(timeout);
        try {
            while (queue.isEmpty()){
                try {
                    if (nanos<=0){
                        return null;
                    }
                    nanos=emptyWaitSet.awaitNanos(nanos);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            T t=queue.removeFirst();
            fullWaitSet.signal();
            return t;
        }finally {
            lock.unlock();
        }

    }
    public T take(){
        lock.lock();
        try {
            while (queue.isEmpty()){
                try {
                    emptyWaitSet.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            T t=queue.removeFirst();
            fullWaitSet.signal();
            return t;
        }finally {
            lock.unlock();
        }
    }
    public void put(T element){
        lock.lock();
        try {
            while (queue.size()==capcity){
                try{
                    fullWaitSet.await();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            queue.addLast(element);
            emptyWaitSet.signal();
        }finally {
            lock.unlock();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Array_new

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

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

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

打赏作者

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

抵扣说明:

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

余额充值