自定义线程池

2020-09-17  本文已影响0人  YAOPRINCESS
package com.kang.multithread;


import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author klr
 * @create 2020-09-17-13:32
 */
public class ThreadPoolTest {

    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(2, 1000, TimeUnit.MILLISECONDS, 10,(queue,task)->{
            //1.死等
//            queue.put(task);
            //2.带超时的等待
//            queue.offer(task, 500, TimeUnit.MILLISECONDS);
            //3.放弃任务
//            System.out.println("放弃任务");
            //4.让调用者抛出异常
//            throw new RuntimeException("任务执行失败" + task);
            //5.让调用者自己执行任务
            task.run();//被主线程调用
        });
        for (int i = 0; i < 5; i++) {
            int j = i;
            threadPool.execute(()->{
                System.out.println(j);
            });
        }
    }
}

//策略模式
@FunctionalInterface
interface RejectPolicy<T>{
    void reject(BlockingQueue<T> queue, T task);
}

//线程池
class ThreadPool{
    //处理策略
    private RejectPolicy<Runnable> rejectPolicy;

    //任务队列
    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);
                worker.start();
            } else {
//                taskQueue.put(task);
                //1.死等  2.带超时等待 3.放弃任务执行    4.抛出异常  5.调用这自己执行任务
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }

    public ThreadPool(int coreSize, long timeout, TimeUnit unit ,int size,RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.unit = unit;
        this.taskQueue = new BlockingQueue<>(size);
        this.rejectPolicy = rejectPolicy;
    }

    class Worker extends Thread{
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            //task不为空,执行任务

            //当task执行完毕,从任务队列获取任务执行

//            while (task!=null||(task=taskQueue.take())!=null){
            while (task!=null||(task=taskQueue.poll(timeout,TimeUnit.MILLISECONDS))!=null){

                try {
                    task.run();
                }finally {
                    task = null;
                }
            }
            synchronized (workers) {
                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 size;

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

    //带超时的阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            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 value) {
        lock.lock();
        try {
            while (queue.size()==size) {
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(value);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    //带超时时间阻塞添加,避免任务超过size,导致阻塞
    public boolean offer(T task, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (queue.size()==size) {
                try {
                    if (nanos <= 0) {
                        return false;
                    }
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            emptyWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }


    //获取大小
    public int size() {
        lock.lock();
        try {
            return queue.size();
        }
        finally {
            lock.unlock();
        }
    }
    //    在try…catch语句中,当程序执行完return后的表达式后,会转而执行finally语句块,最后再继续执行return。


    public  void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            if (queue.size() == size) {

                rejectPolicy.reject(this,task);

            } else {//有空闲
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        }
        finally {
            lock.unlock();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读