线程池Demo

public class MyThreadPoolExcutor {

    private int corePoolSize;//核心线程数
    private int maxPoolSize;//最大线程数
    private LinkedBlockingQueue<Runnable> workQueue;//存放任务的队列(仓库)
    //JUC并发包下的类Atomic,基础类型原子操作封装类,保证类似于i++这类操作的原子性
    AtomicInteger currentPoolSize = new AtomicInteger(0);//当前线程池的大小

    public MyThreadPoolExcutor(int corePoolSize, int maxPoolSize,int workQueueSize) {
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        workQueue=new LinkedBlockingQueue<>(workQueueSize);
    }

    //Worker类的一个对象就代表线程池中的一个线程
    public class Worker extends  Thread{

        Runnable firstTask;

        //currentPoolSize<corePoolSize执行的任务
        public Worker(Runnable firstTask){
            this.firstTask=firstTask;
        }

        @Override
        public void run() {
            //执行用户提交的runnable
            try {
                Runnable task = firstTask;
                //利用循环保证线程的复用,即在执行完run()方法后不会被销毁
                //take()从任务队列取runnable执行,如果队列里面没有数据,阻塞,线程等待有任务进来然后继续执行代码
                while (task != null || (task = workQueue.take()) != null) {
                    task.run();
                    task = null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public void execute(Runnable task) throws Exception {
    //1.如果正在运行的线程数小于corePoolSize,那么马上创建线程(Worker)运行这个任务。
    if(currentPoolSize.get()<corePoolSize){
        if(currentPoolSize.incrementAndGet()<=corePoolSize) {  //当前线程池大小+1,再进行判断
            new Worker(task).start();
            return;
        }else{//如果当前运行的线程数currentPoolSize超过了corePoolSize
            currentPoolSize.decrementAndGet();  //currentPoolSize-1
        }
    }
    //2.如果正在运行的线程数大于或者等于corePoolSize,那么将这个任务放入队列
        if(workQueue.offer(task)){
            return;
        }
     //3.如果这个时候队列满了,而且正在运行的线程数量小于maxPoolSize,那么还是要创建线程运行这个任务。
        if(currentPoolSize.get()<maxPoolSize){
            if(currentPoolSize.incrementAndGet()<=maxPoolSize) {  //当前线程池大小+1,再进行判断
                new Worker(task).start();
                return;
            }else{//如果当前运行的线程数currentPoolSize超过了corePoolSize
                currentPoolSize.decrementAndGet();  //currentPoolSize-1
            }
        }
        //4.如果队列满了,当前线程数大于或等于maxPoolSize,就抛出异常拒绝执行这个任务
        throw new Exception("拒绝执行");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值