java - 手写定长线程池

package com.gpdi.operatingunit.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @description: 固定线程池大小的线程池
 * @author: Lxq
 * @date: 2020/1/10 14:33
 */
public class MyNewFixedSizeThreadPool {
    /**
     * 任务队列
     */
    private BlockingQueue queue;

    /**
     * 工作线程集合
     */
    private List<Thread> workers;

    /**
     * 线程池工作的标识
     */
    private volatile boolean working = true;


    /**
     * @param poolSize      线程池数量
     * @param tastQueueSize 任务队列的长度
     */
    public MyNewFixedSizeThreadPool(int poolSize, int tastQueueSize) {
        if (poolSize <= 0 || tastQueueSize <= 0) {
            throw new IllegalArgumentException("参数错误");
        }
        // 阻塞队列LinkedBlockingQueue
        queue = new LinkedBlockingQueue(tastQueueSize);

        // 将工作线程包装为线程安全的集合
        this.workers = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < poolSize; i++) {
            Worker w = new Worker(this);
            w.start();
            this.workers.add(w);
        }
    }


    /**
     * 提交线程
     *
     * @param task
     * @return
     */
    public boolean submit(Runnable task) {
        return this.queue.offer(task);
    }


    /**
     * 关闭线程池
     */
    public void shutdown() {
        this.working = false;

        // 把阻塞的线程中断
        for (Thread t : this.workers) {
            if (t.getState().equals(Thread.State.BLOCKED)
                    || t.getState().equals(Thread.State.WAITING)
                    || t.getState().equals(Thread.State.TIMED_WAITING)) {
                t.interrupt();
            }
        }
    }

    /**
     * 执行线程
     */
    private class Worker extends Thread {

        private MyNewFixedSizeThreadPool pool;
        public Worker(MyNewFixedSizeThreadPool pool) {
            super();
            this.pool = pool;
        }
        @Override
        public void run() {
            while (this.pool.working || this.pool.queue.size() > 0) {
                //执行任务
                Runnable task = null;
                try {
                    if (this.pool.working) {
                        task = (Runnable) this.pool.queue.take();
                    }else {
                        task = (Runnable) this.pool.queue.poll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (task !=null){
                    task.run();
                    System.out.println(Thread.currentThread().getName());
                }
            }
        }
    }


}

测试:

public class Test {

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

        MyNewFixedSizeThreadPool pool = new MyNewFixedSizeThreadPool(3,6);
        for (int i = 0; i < 7; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(1);
                }
            });
        }
        pool.shutdown();

    }
}
发布了35 篇原创文章 · 获赞 22 · 访问量 974

猜你喜欢

转载自blog.csdn.net/weixin_38982591/article/details/103924956