简单来说 Executor 和 Worker 构成了生产者消费者的模型,临界资源使用BlockQueue存储
而Worker作为消费者可以简化为以下伪代码
private BlockQueue<Runnable> workQueue = new BlockQueue<>();
public class Worker implements Runnable {
public void run() {
runWorker();
}
public void runWorker(){
Runnable task;
while ((task = workQueue.take()) != null) {
task.run();
}
}
}
而Executor作为生产者可以简化为以下伪代码
public class Executor {
public void execute(Runnable command) {
if(isRunning()) {
// 根据现有线程个数判断是推送临界区workQueue.offer(command)
// 还是 addWorker (Runnable)
} else {
reject(command);
}
}
}