java-手写线程池

在这里插入图片描述

原理:

  • ThreadPool包含两大组件:BlockQueue和ThreadPool
  • 线程达到上线之后,新进的任务都会进入BlockQueue
  • 线程完成当前任务后会从BlockQueue中获取新的任务
package thread.pool;


import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyPool {

    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool(2, 3, 1, new RejectPolicy<Runnable>() {
            @Override
            public void reject(BlockQueue<Runnable> queue, Runnable task) {
                // 线程池忙,拒绝接收任务时的策略,可自定义 
                // 1,什么都不干
                System.out.println("插入失败,什么都不干");
            }
        });


        // 模拟加入10个任务
        for (int i=0 ;i<10 ;i++) {
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("task" + Thread.currentThread().getName());
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

@FunctionalInterface // 拒绝策略
interface RejectPolicy<T> {
    void reject(BlockQueue<T> queue, T task);
}

class ThreadPool{
   // 线程数
    private int core;
    // 等待加入队列的最大等待时间,超出时间结束线程或者告知调用者加入任务失败
    private long timeOut;
    private BlockQueue<Runnable> blockQueue;
    private List<Work> workers = new ArrayList<>();
    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int core, int queueSize, long timeOut) {
        this.core = core;
        blockQueue = new BlockQueue<>(queueSize);
        this.timeOut = timeOut;
    }

    public ThreadPool(int core, int queueSize, long timeOut,RejectPolicy<Runnable> rejectPolicy) {
        this.core = core;
        blockQueue = new BlockQueue<>(queueSize);
        this.rejectPolicy = rejectPolicy;
        this.timeOut = timeOut;
    }

    public void execute(Runnable task) {
        synchronized (workers) {
            if (workers.size() < core) {
                Work work = new Work(task);
                workers.add(work);
                work.start();
            } else {
//                blockQueue.put(task);
                boolean success = blockQueue.offer(task, timeOut, TimeUnit.SECONDS);
                if (!success) {
                    rejectPolicy.reject(blockQueue,task);
                }
            }
        }
    }

    class Work extends Thread{
        private Runnable task;
        public Work(Runnable task) {
          this.task = task;
        }

        @Override
        public void run() {
            while (task!=null ||(task=blockQueue.poll())!=null) {
                try {
                    task.run();
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    task = null;
                }
            }
        }
    }

}



class BlockQueue<T> {
    private volatile LinkedList<T> pool = new LinkedList<>();
    private ReentrantLock lock = new ReentrantLock();
    private Condition emptyCondition = lock.newCondition();
    private Condition fullCondition = lock.newCondition();

    private int queueSize;

    public BlockQueue(int queueSize) {
        this.queueSize = queueSize;
    }

    // 带超时时间阻塞添加
    public boolean offer(T task, long timeout, TimeUnit timeUnit) {
        lock.lock();
        long nanos = timeUnit.toNanos(timeout);
        try {
            while (pool.size() == queueSize) {
                if (nanos < 0) {
                    System.out.println("=====插入超时:" + task);
                    return false;
                }
                nanos = fullCondition.awaitNanos(nanos);
            }
            System.out.println("插入队列:" + task);
            pool.add(task);
            emptyCondition.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return true;
    }

    public void put(T task) {
        lock.lock();
        try {
            while (pool.size() == queueSize) {
                fullCondition.await();
            }
            System.out.println("插入队列:" + task);
            pool.add(task);
            emptyCondition.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public T poll() {
        lock.lock();
        try {
            while (pool.size() == 0) {
                try {
                    emptyCondition.await();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            T t = pool.removeFirst();
            System.out.println("溢出队列:" + t);
            fullCondition.signal();
            return t;

        } finally {
            lock.unlock();
        }
    }

    // 带超时阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        long nanos = unit.toNanos(timeout);
        try {
            while (pool.size() == 0) {
                try {
                    if (nanos < 0) {
                        return null;
                    }
                    // 防止虚假唤醒
                   nanos = emptyCondition.awaitNanos(nanos);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            T t = pool.removeFirst();
            System.out.println("溢出队列:" + t);
            fullCondition.signal();
            return t;

        } finally {
            lock.unlock();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小手追梦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值