JDK并发--并发02--线程池

一、简单线程池实现

  1. 执行器,
    1. 作用:执行线程,内部存在包含真正执行任务的线程threads
    2. 其中容器出错的点,是初始化线程之后,需要让线程处于死循环中,这样才可以不断的接受来自队列中的任务,进行执行。
public class MyExecutor {

    private final int poolSize;

    private final RunnableTaskQueue runnableTaskQueue;

    private final List<Thread> threads = new ArrayList<>();

    public MyExecutor(int poolSize){
        this.poolSize = poolSize;
        runnableTaskQueue = new RunnableTaskQueue();
        Stream.iterate(1,item->item+1).limit(poolSize).forEach(item->{
            initThread();
        });
    }

    private void initThread() {
        if(threads.size()<=poolSize){
            Thread thread = new Thread(()->{
                //让核心线程不断的去获取任务
                //容易丢失死循环,导致,线程就执行一次
                while (true) {
                    Runnable task = runnableTaskQueue.getTask();
                    task.run();
                }
            });
            threads.add(thread);
            thread.start();
        }
    }


    public void execute(Runnable runnable){
        runnableTaskQueue.addTask(runnable);
    }
}
  1. 任务队列
//任务队列
public class RunnableTaskQueue {

    private final LinkedList<Runnable> tasks = new LinkedList<>();

    //增加任务
    public void addTask(Runnable task){
        synchronized (this.tasks){
            tasks.add(task);
            tasks.notifyAll();
        }
    }

    //获取任务
    public Runnable getTask() {
        synchronized (this.tasks){
            while (tasks.isEmpty()){
                System.out.println("线程【"+Thread.currentThread().getName()+"】进入等待状态");
                try {
                    tasks.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return tasks.removeFirst();
        }
    }
}
  1. 测试类
public class Test {

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

        MyExecutor executor = new MyExecutor(5);

        for (int i= 0 ;i<10;i++){
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " execute this task");
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        try {
            Thread.currentThread().sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(System.in.read());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值