线程池模型实现

代码中附注解

public class MyThreadpool {
    private static class Worker extends Thread{
        //创建队列存放线程
        private BlockingQueue<Runnable> queue = null;
        //工作类构造方法传入线程队列
        Worker(BlockingQueue<Runnable> queue){
            super("员工");
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                //工作方式为,如果没有线程要求停止,就从队列中取线程启动:
                while (!Thread.interrupted()) {
                    Runnable command = queue.take();
                    command.run();
                }
            }catch (InterruptedException e){

            }
        }
    }
    //设置正式员工数量
    private int corePoolSize = 10;
    //当前员工数量
    private int currentPooolSize = 0;
    //员工列表
    private List<Worker> workerList = new ArrayList<>();
    //任务队列,传给Worker类,同步queue中任务;
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    
    public void execute(Runnable command){
        if(currentPooolSize < corePoolSize){
            Worker worker = new Worker(queue);
            worker.start();
            workerList.add(worker);
            currentPooolSize++;
        }
        queue.add(command);
    }

    public void shutDown() throws InterruptedException {
        //通知各个工作线程将要停工
        for (Worker worker : workerList){
            worker.interrupt();
        }
        //等待每个员工停工
        for (Worker worker : workerList){
            worker.join();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadpool pool = new MyThreadpool();
        pool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("吃饭");
            }
        });
        Thread.sleep(5000);
        pool.shutDown();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值