线程池实现

线程池实现

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

public class ThreadPool {
    public static void main(String[] args) throws InterruptedException {
        ThreadPool test=new ThreadPool(4,8,5);
        Random random=new Random();
        for(int i=0;i<1000;i++) {
            int finalI = i;
            Runnable r=()->{
                int count=random.nextInt(10^2);
                while(count>0){
                    count--;
                }
                System.out.println("任务"+ finalI);
            };
            test.submit(r);
        }
        test.shutdown();

    }
    private int coreThreadCount;
    private int maxThreadCount;
    private int queueSize;
    private ArrayBlockingQueue<Runnable> queue;
    private ArrayList<Thread> threads;

    public ThreadPool(int coreThreadCount, int maxThreadCount, int queueSize) {
        this.coreThreadCount = coreThreadCount;
        this.maxThreadCount = maxThreadCount;
        this.queueSize = queueSize;
        queue=new ArrayBlockingQueue<>(queueSize);
        threads=new ArrayList<>();
    }
    public void submit(Runnable runnable) throws InterruptedException {
        if(coreThreadCount>threads.size()){
            queue.put(runnable);
            Thread t=new MyThread(queue);
            t.start();
            threads.add(t);
        }else if(queue.size()==queueSize) {
            if (threads.size() == maxThreadCount) {
                //System.out.println("队列已满, 提交任务失败");
                queue.put(runnable);
            } else {
                queue.put(runnable);
                Thread t=new MyThread(queue);
                t.start();
                threads.add(t);
            }
        }else{
            queue.put(runnable);
        }
    }
    public void shutdown(){
        System.out.printf("一共启动了%d个线程",threads.size());
        for(Thread thread:threads){
            thread.interrupt();
        }
    }
    private class MyThread extends Thread{
        private ArrayBlockingQueue<Runnable> queue;
        public MyThread(ArrayBlockingQueue queue){
            this.queue=queue;
        }
        @Override
        public void run(){
            try {
                while(true) {
                    Runnable runnable = queue.take();
                    runnable.run();
                }
            } catch (InterruptedException e) {
                System.out.println(getName()+":正常结束");
            }
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值