您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

创建动态(增长/缩小)线程池

创建动态(增长/缩小)线程池

可能会帮助您的一个技巧是分配一个RejectedExecutionHandler使用相同线程的作业,以将作业提交到阻塞队列。这将阻塞当前线程,并消除对某种循环的需要。

这是从该答案中复制的拒绝处理程序。

final BlockingQueue queue = new ArrayBlockingQueue<Runnable>(200);
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(nThreads, nThreads,
       0L, TimeUnit.MILLISECONDS, queue);
// by default (unfortunately) the ThreadPoolExecutor will call the rejected
// handler when you submit the 201st job, to have it block you do:
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
   public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
      // this will block if the queue is full
      executor.getQueue().put(r);
   }
});

然后,您应该能够使用的核心/最大线程数的,只要你意识到有界阻塞队列你使用首先填满芯线上面创建的线程之前。因此,如果您有10个核心线程,并且希望第11个作业启动第11个线程,那么您将需要具有大小为0的阻塞队列(可能是aSynchronousQueue)。我觉得这是本来不错的ExecutorService课程的真正限制。

其他 2022/1/1 18:27:17 有493人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶