简化版线程池

TaskChannel:任务分配接口,返回null表示终止运行

public interface TaskChannel {
    // 当返回null值,表示线程可停止运行
    Runnable get() throws InterruptedException;
}

ThreadNode:不断获取任务并运行的线程

public class ThreadNode {
    private TaskChannel taskChannel;

    public void start() {
        (new Thread(() -> {
            try {
                // 不断循环获取任务并执行
                Runnable runnable;
                while ((runnable = taskChannel.get()) != null) {
                    try {
                        runnable.run();
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        })).start();
    }

    public void setTaskChannel(TaskChannel taskChannel) {
        this.taskChannel = taskChannel;
    }
}

线程池主代码:通过BlockingQueue存储任务,实现TaskChannel实现获取任务和没任务时挂起现成的操作

public class EasyThreadPool {
    private int coreThreadSize;
    private int maxThreadSize;
    private Consumer reject;
    // 当前线程数
    private AtomicInteger threadSize = new AtomicInteger(0);
    // 空闲线程数
    private AtomicInteger waitingSize = new AtomicInteger(0);

    private BlockingQueue queue = new ArrayBlockingQueue<>(128);

    public EasyThreadPool(int coreThreadSize, int maxThreadSize, Consumer reject) {
        this.coreThreadSize = coreThreadSize;
        this.maxThreadSize = maxThreadSize;
        this.reject = reject;
    }

    public int getThreadSize() {
        return threadSize.intValue();
    }

    private void createWorker() {
        if(this.threadSize.incrementAndGet() > maxThreadSize) {
           this.threadSize.decrementAndGet();
           return ;
        }

        ThreadNode node = new ThreadNode();
        node.setTaskChannel(() -> {
            Runnable task = null;
            while ((task = this.queue.poll(5, TimeUnit.SECONDS)) == null) {
                synchronized (EasyThreadPool.this) {
                    // 双重判断,防止出现线程未完全进入等待状态时,有任务进来
                    if((task = this.queue.poll()) != null || waitingSize.intValue() > coreThreadSize) {
                        break;
                    }
                    waitingSize.incrementAndGet();
                    EasyThreadPool.this.wait();
                    waitingSize.decrementAndGet();
                }
            }

            if(task == null) {
                this.threadSize.decrementAndGet();
            }
            return task;
        });
        node.start();
    }

    public void addTask(Runnable task) {
        boolean isAdd = this.queue.add(task);
        // 过载执行拒绝策略
        if (!isAdd) {
            this.reject.accept(task);
            return;
        }

        if (this.threadSize.intValue() < maxThreadSize && this.queue.size() > 2) {
            this.createWorker();
        }

        // 唤醒闲置线程
        synchronized (this) {
            if (this.waitingSize.intValue() > 0) {
                this.notify();
            }
        }
    }
}

Demo代码

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        int size1 = Thread.currentThread().getThreadGroup().activeCount();
        System.out.println("real thread size:" + size1);
        EasyThreadPool threadPool = new EasyThreadPool(4,8, System.out::println);
        for (int i = 0; i < 20; i++) {
            threadPool.addTask(()->{
                int size = Thread.currentThread().getThreadGroup().activeCount();
                System.out.println("real thread size:" + size);
                System.out.println("task:" + System.currentTimeMillis() / 1000);
            });
        }
        Thread.sleep(8000);
        System.out.println("ts:" + threadPool.getThreadSize());
        for (int i = 0; i < 20; i++) {
            Thread.sleep(1000);
            threadPool.addTask(()->{
                int size = Thread.currentThread().getThreadGroup().activeCount();
                System.out.println("real thread size:" + size);
                System.out.println("thread size:" + threadPool.getThreadSize());
            });
        }
    }
}

你可能感兴趣的:(简化版线程池)