线程池实现
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()+":正常结束");
}
}
}
}