目前业界线程池的设计,普遍采用的都是生产者 - 消费者模式。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class MyThreadPool {
//阻塞队列实现生产者-消费者模式
BlockingQueue<Runnable> workQueue;
//内部工作线程
List<WorkThread> threads = new ArrayList<>();
public MyThreadPool(int poolSize, int queueSize) {
this.workQueue = new LinkedBlockingQueue<>(queueSize);
//创建工作线程
for(int idx = 0; idx < poolSize; idx++) {
WorkThread work = new WorkThread();
work.start();
threads.add(work);
}
}
//提交任务
void execute(Runnable command) {
try {
workQueue.put(command);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//工作线程负责消费任务,并执行任务
class WorkThread extends Thread {
public void run() {
while(true) {
try {
Runnable task = workQueue.take();
task.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//创建线程池
MyThreadPool pool = new MyThreadPool(6, 18);
//提交任务
pool.execute(()->{ System.out.println(Thread.currentThread() + " - demo"); });
}
}