手写一个简单的JAVA线程池

最近项目中用到了线程池,俗话说的好,了解他才能打败他,于是自己写了一个简单的线程池拿来实验

1、线程接口,定义线程池中的主要的几个方法

import java.util.List;

/**
 * @Author: wuyaohua
 * @Description: 线程接口
 * @Date: Created in 11:33 2018-08-21
 */
public interface IThreadPool {
    /**
      * @Author : wuyaohua
      * @Date : 2018-08-21  11:34
      * @Description :  加入任务
      * @Param : [task]
      * @Return : void
    */
    void execute(Runnable task);

    /**
     * @Author : wuyaohua
     * @Date : 2018-08-21  11:34
     * @Description :  加入任务
     * @Param : [task]
     * @Return : void
     */
    void execute(Runnable[] tasks);

    /**
     * @Author : wuyaohua
     * @Date : 2018-08-21  11:34
     * @Description :  加入任务
     * @Param : [task]
     * @Return : void
     */
    void execute(List<Runnable> tasks);

    /**
     * @Author : wuyaohua
     * @Date : 2018-08-21  11:34
     * @Description :  销毁线程
     * @Param : [task]
     * @Return : void
     */
    void destroy();
}

2、线程池实现类

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author: wuyaohua
 * @Description: 线程池实现类
 * @Date: Created in 11:35 2018-08-21
 */
@SuppressWarnings("ALL")
public class ThreadPoolImpl implements IThreadPool {
    /**
     * 默认开启线程个数
     */
    static int WORKER_NUMBER = 5;
    /**
     * 完成任务线程数 可见性
     */
    static volatile int sumCount = 0;
    /**
     * 任务队列 list非线程安全,可以优化为BlockingQueue
     */
    static List<Runnable> taskQueue = new LinkedList<Runnable>();
    /**
     * 线程工作组
     */
    WorkerThread[] workThreads;
    /**
    * 原子性
    */
    static AtomicLong threadNum = new AtomicLong();

    static ThreadPoolImpl threadPool;

    //构造方法
    public ThreadPoolImpl() {
        this(WORKER_NUMBER);
    }

    public ThreadPoolImpl(int workerNum) {
        ThreadPoolImpl.WORKER_NUMBER = workerNum;
        //开辟工作线程空间
        workThreads = new WorkerThread[WORKER_NUMBER];
        //开始创建工作线程
        for (int i = 0; i < WORKER_NUMBER; i++) {
            workThreads[i] = new WorkerThread();
            Thread thread = new Thread(workThreads[i], "ThreadPool-worker" + threadNum.incrementAndGet());
            System.out.println("初始化线程数" + (i + 1) + "---------当前线程名称:" + thread.getName());
            thread.start();
        }
    }

    @Override
    public String toString() {
        return "工作线程数量为" + WORKER_NUMBER
                + "已完成的任务数" + sumCount +
                "等待任务数量" + taskQueue.size();
    }


    //获取线程池
    public static IThreadPool getThreadPool() {
        return getThreadPool(WORKER_NUMBER);
    }

    public static IThreadPool getThreadPool(int workerNum) {
        //容错性,如果小于等于0就默认线程数
        if (workerNum <= 0) {
            workerNum = WORKER_NUMBER;
        }
        if (threadPool == null) {
            threadPool = new ThreadPoolImpl(workerNum);
        }
        return threadPool;
    }


    @Override
    public void execute(Runnable task) {
        synchronized (taskQueue) {
            taskQueue.add(task);
            taskQueue.notifyAll();
        }
    }

    @Override
    public void execute(Runnable[] tasks) {
        synchronized (taskQueue) {
            for (Runnable task : tasks) {
                taskQueue.add(task);
            }
            taskQueue.notifyAll();
        }
    }

    @Override
    public void execute(List<Runnable> tasks) {
        synchronized (taskQueue) {
            for (Runnable task : tasks) {
                taskQueue.add(task);
            }
            taskQueue.notifyAll();
        }
    }

    @Override
    public void destroy() {
        //循环是否还存在任务,如果存在等待20毫秒处理时间
        while (!taskQueue.isEmpty()) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果任务队列已处理完成,销毁线程,清空任务
        for (int i = 0; i < WORKER_NUMBER; i++) {
            workThreads[i].setWorkerFlag();
            workThreads[i] = null;
        }
        threadPool = null;
        taskQueue.clear();
    }


    /**
     * 创建工作线程池
     */
    class WorkerThread extends Thread {
        /**
        * 用来标识当前线程属于活动可用状态
        */
        private boolean isRunning = true;

        @Override
        public void run() {
            Runnable runnable = null;
            //死循环
            while (isRunning) {
                //非线程安全,所以采用同步锁
                synchronized (taskQueue) {
                    while (isRunning && taskQueue.isEmpty()) {
                        try {
                            //如果任务队列为空,等待20毫秒 监听任务到达
                            taskQueue.wait(20);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //任务队列不为空
                    if (!taskQueue.isEmpty()) {
                        //获取第一个任务
                        runnable = taskQueue.remove(0);
                    }
                }
                if (runnable != null) {
                    runnable.run();
                }
                sumCount++;
                runnable = null;
            }
        }

        /**
        * 销毁线程
        */
        public void setWorkerFlag() {
            isRunning = false;
        }
    }
}

3、线程池测试类

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wuyaohua
 * @Description: 线程池测试类
 * @Date: Created in 11:41 2018-08-21
 */
public class ThreadPoolTest {
    public static void main(String[] args) {
        //获取线程池
        IThreadPool t = ThreadPoolImpl.getThreadPool(20);

        List<Runnable> taskList = new ArrayList<Runnable>();
        for (int i = 0; i < 100; i++) {
            taskList.add(new Task());
        }
        //执行任务
        t.execute(taskList);
        System.out.println(t);
        //销毁线程
        t.destroy();
        System.out.println(t);
    }

    static class Task implements Runnable {

        private static volatile int i = 1;

        @Override
        public void run() {
            System.out.println("当前处理的线程:" + Thread.currentThread().getName() + " 执行任务" + (i++) + " 完成");
        }
    }
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值