源码 ThreadPoolExecutor(2. 任务的消费者-Worker)

简单来说 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);
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容