首页 文章

等待线程在java中的线程池中可用

提问于
浏览
-4

我在JAVA中使用executorservice进行线程池化 . 有没有一种方法可以让我在执行服务中的线程池中等待线程可用,并且仅在池中有可用线程时才继续

1 回答

  • 0

    拥有ExecutorService的重点不在于处理线程,所以除非你有一个非常具体的理由来跟踪它们的状态,否则你应该避免这样做 .

    您还可以向池中添加任意数量的任务,执行程序将全部运行它们 .

    例如:

    final List<Callable<Boolean>> tasks = new ArrayList<>(10);
    for (int i=0;i<10;i++) tasks.add(()->{
        //something time consuming
        return true;
    });
    
    final ExecutorService executor = Executors.newFixedThreadPool(5);
    List<Future<Boolean> handles = executor.invokeAll(tasks);
    
    for (Future<Boolean> handle : handles) {
        handle.get();
    }
    
    // here all the 10 tasks have been completed by the 5 thread pool
    

    请注意,每次调用handle.get()返回时,池中的线程理论上都可用,但执行程序将立即重用它来运行下一个等待任务 .

相关问题