Java自定义线程池ThreadPool


public class SelfThreadPool {
    //线程池中默认线程的个数为5
    private static int WORK_NUM = 5;
    //队列默认任务个数为100
    private static int TASK_COUNT = 100;

    //工作线程组
    private WorkThread[] workThreads;

    //任务队列
    private final BlockingQueue<Runnable> queue;
    private final int worker_num; //用户构造构造池子时希望启动的线程数

    public SelfThreadPool() {
        this(WORK_NUM, TASK_COUNT);
    }
    public SelfThreadPool(int worker_num, int taskCount) {
        if (worker_num<=0) worker_num = WORK_NUM;
        if(taskCount<=0) taskCount = TASK_COUNT;
        this.worker_num = worker_num;
        this.queue = new ArrayBlockingQueue<>(taskCount);
        this.workThreads = new WorkThread[worker_num];
        for (int i = 0; i < worker_num; i++) {
            workThreads[i] = new WorkThread();
            workThreads[i].start();
        }
    }

    //执行任务,其中只是把任务加入队列,何时执行由线程池管理器决定
    public void execute(Runnable task) {
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //销毁线程池,该方法保证在所有任务都完成的情况下才销毁线程池,否则等待任务完成才销毁
    public void destroy() {
        //工作线程停止,且置为null
        System.out.println("ready close pool......");
        for (int i = 0; i < worker_num; i++) {
            workThreads[i].stopWorker();
            workThreads[i] = null;
        }
        queue.clear();//清空任务队列
    }

    @Override
    public String toString() {
        return "WorkThread number: " + worker_num + " wait task number: " + queue.size();
    }

    /**
     * 内部类,工作线程
     */
    private class WorkThread extends Thread {
        @Override
        public void run() {
            Runnable r = null;
            try {
                while (!isInterrupted()) {
                    r = queue.take();
                    if (r != null) {
                        System.out.println("Thread" + getId() + "is executing");
                        r.run();
                    }
                    r = null; //help gc
                }
            } catch (Exception e) {

            }
        }

        public void stopWorker() {
            interrupt();
        }
    }
}

public class SelfThreadPoolClient {
    public static void main(String[] args) throws InterruptedException {
        SelfThreadPool t = new SelfThreadPool(3, 0);
        t.execute(new MyTask("testA"));
        t.execute(new MyTask("testB"));
        t.execute(new MyTask("testC"));
        t.execute(new MyTask("testD"));
        t.execute(new MyTask("testE"));
        System.out.println(t);
        Thread.sleep(10000);
        t.destroy();// 所有线程都执行完成才destory
        System.out.println(t);
    }

    // 任务类
    static class MyTask implements Runnable {

        private String name;
        private Random r = new Random();

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {// 执行任务
            try {
                Thread.sleep(r.nextInt(1000)+2000);
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getId()+" sleep InterruptedException:"
                        +Thread.currentThread().isInterrupted());
            }
            System.out.println("任务 " + name + " 完成");
        }
    }
}

//输出结果
Thread12 is executing
Thread13 is executing
WorkThread number: 3 wait task number: 2
Thread14 is executing
任务 testB 完成
Thread14 is executing
任务 testA 完成
Thread12 is executing
任务 testC 完成
任务 testD 完成
任务 testE 完成
ready close pool......
WorkThread number: 3 wait task number: 0

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值