自定义实现线程池

package com.spring.security.demo.securitydemo.util.Thrend;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 流程:
 * 1. 成员变量:
 *      初始化线程数量;
 *      链表堵塞队列;
 *      结束线程池标识;
 * 2. 创建有参构造方法初始化线程数量,并调用“线程任务内部类”;
 * 3. 创建“线程任务内部类”,用于执行队列中的任务(把队列中的任务交给线程管理);
 * 4. 创建添加任务方法add();
 * 5. 创建结束线程池方法closure();
 *
 * @Author qizhentao
 * @Date 2020/6/10 11:20
 * @Version 1.0
 */
public class ThreadExecutor {

    // 1.初始化线程数量
    private int threadCount;

    // 1.2.链表堵塞式任务队列(存放需要执行的任务,poll先进先出)
    private BlockingQueue taskQueue = new LinkedBlockingQueue<>();

    // 1.3.结束任务标识
    private boolean closure = true;

    // 2.初始化线程池
    public ThreadExecutor(int threadCount){
        this.threadCount = threadCount;

        // 循环创建线程(内部类)来执行任务
        for (int a = 0; a < threadCount; a++){
            RunTask runTask = new RunTask();
            runTask.start();// start()后将会执行内部类中的run()
        }
    }

    // 2.1.内部线程类-执行任务类
    class RunTask extends Thread{
        @Override
        public void run() {
            while (closure || taskQueue.size() > 0){
                Runnable poll = taskQueue.poll(); // 获取未被执行的任务
                if(poll != null){
                    poll.run();// 执行任务
                }
            }
        }
    }

    // 3.添加任务
    public void add(Runnable runnable){
        this.taskQueue.add(runnable);
    }

    // 3.1.结束任务方法
    public void closure(){
        this.closure = false;
    }


    // 测试使用
    public static void main(String[] args) {
        // 1.初始化线程池
        ThreadExecutor threadExecutor = new ThreadExecutor(2);

        for (int i = 0; i < 10; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":task");
                }
            };
            // 2.将任务装入线程池中的任务队列中
            threadExecutor.add(runnable);
        }

        // 3.释放线程池
        threadExecutor.closure();
    }

}

 

你可能感兴趣的:(线程)