java java中带有invokeAll()和Future的ExecutorService

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12896755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:41:04  来源:igfitidea点击:

ExecutorService with invokeAll() and Future in java

java

提问by fen1ksss

Having the following code at hand:

手头有以下代码:

    ExecutorService executor = Executors.newFixedThreadPool(10);
    Collection collection = new ArrayList();
    for (int n=1; n<100; n++)
        collection.add(new MyThread(n));

    try {
        List<Future<Boolean>> futures = executor.invokeAll(collection);

        for(Future<Boolean> future : futures){
            future.get();
            if (future.isDone()) {
                System.out.println("true");
            }
            else
                System.out.println("false");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

If the above is correct?
And if all future.isDone()are true, then all of the threads have been done?
How can I make a flag, to be sure that all of them are done?

以上是否正确?
如果一切future.isDone()都是真的,那么所有的线程都已经完成了?
我怎样才能制作一面旗帜,以确保所有这些都完成了?

采纳答案by gabrjan

To check if all are true, you can do something like this:

要检查是否全部正确,您可以执行以下操作:

boolean works=true;
  for(Future<Boolean> future : futures){
        future.get();
        if (future.isDone()) {
            System.out.println("true");
        }
        else{
            System.out.println("false");works=false;
        }
    }
if(works)System.out.println("yea it works")

回答by user1372408

Meant as a comment on vainolo's reply but I don't have enough reputation points:

作为对 vainolo 回复的评论,但我没有足够的声望点:

isDoneis also redundant because invokeAllreturns a list of futures for which isDoneis true. The javadocs mention this.

isDone也是多余的,因为invokeAll返回isDone为真的期货列表。javadocs提到了这一点

回答by Juvanis

Using a boolean variable is the simplest way to understand that all threads are done. Another way could be using a primitive, e.g. an integer. You could simply increment/decrement the counter to see if all threads are done.

使用布尔变量是理解所有线程都已完成的最简单方法。另一种方法是使用原语,例如整数。您可以简单地增加/减少计数器以查看是否所有线程都已完成。

And another way could be checking the return value of awaitTermination()invocation on your ExecutorServiceobject.

另一种方法可能是检查对象上awaitTermination()调用的返回值ExecutorService

  int counter = 0;

  for(Future<Boolean> future : futures)
  {
        future.get();            
        if (future.isDone())
            System.out.println("true");
        else
        {
            counter++;
            System.out.println("false");
        }
   }

   if(counter != 0)
       System.out.println("DONE!");

   // Another way of checking all threads are done.
   if(executor.awaitTermination(100, TimeUnit.SECONDS))
       System.out.println("DONE!");

回答by Peter Lawrey

Normally you add Runnable tasks to a Thread pool. Adding Threads to a thread pool isn't going to do what you think.

通常,您将 Runnable 任务添加到线程池中。将线程添加到线程池不会按照您的想法行事。

When future.get() returns for each task, all the tasks have completed. The threads which ran the tasks will still be running.

当 future.get() 为每个任务返回时,所有任务都已完成。运行任务的线程仍将运行。

If you want to stop all the thread once the tasks have completed you can use executor.shutdown();and executor.awaitTermination

如果您想在任务完成后停止所有线程,您可以使用executor.shutdown();executor.awaitTermination



The way I would write it is

我会写它的方式是

ExecutorService executor = Executors.newFixedThreadPool(10);
List<Future<Boolean>> futures = new ArrayList<>();
for (int n = 0; n < 100; n++)
    futures .add(executor.submit(new MyTask(n));

for(Future<Boolean> future : futures) {
    boolean result = future.get();
    // do something with the result.
}

If the result is not needed to you make the type Future<Void>or Future<?>or just Future

如果结果不需要您制作类型Future<Void>Future<?>或只是Future

回答by saum22

initialize a variable check with value =1 and update the value in the else .then check the value of check after the loop has executed

用值 =1 初始化一个变量检查​​并更新 else 中的值。然后在循环执行后检查 check 的值

       if (future.isDone()) {
             System.out.println("true");
        }
        else
            {System.out.println("false");
             check=0;}

回答by vainolo

If the method future.getreturns then the computation done by the future is finished, so calling isDoneis redundant. And yes, after all futures have finished all of the threads in the ThreadPoolshould be available.

如果方法future.get返回,则未来完成的计算完成,因此调用isDone是多余的。是的,在所有期货都完成之后,ThreadPool应该可以使用中的所有线程。

回答by Vishnu

Invokeall calling this method waits complete all take then CPU execution reaches to for loop to check for completion Or Do we need do .. While loop To check completion of tasks

Invokeall 调用此方法等待完成所有时间,然后 CPU 执行到达 for 循环以检查完成 或者我们需要做 .. While 循环来检查任务的完成