Is it a good way to use java.util.concurrent.FutureTask?

后端 未结 6 1092
清歌不尽
清歌不尽 2020-12-22 20:18

First of all, I must say that I am quite new to the API java.util.concurrent, so maybe what I am doing is completely wrong.

What do I want to do?

I have a Ja

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 20:45

    Yuval's solution is fine. As an alternative you can also do this:

    ExecutorService executor = Executors.newFixedThreadPool();
    FutureTask futureOne = new FutureTask(myFirstProcess);
    FutureTask futureTwo = new FutureTask(mySecondProcess);
    executor.execute(futureOne);
    executor.execute(futureTwo);
    executor.shutdown();
    try {
      executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
      // interrupted
    }
    
    
    

    What is the advantage of this approach? There's not a lot of difference really except that this way you stop the executor accepting any more tasks (you can do that the other way too). I tend to prefer this idiom to that one though.

    Also, if either get() throws an exception you may end up in a part of your code that assumes both tasks are done, which might be bad.

    提交回复
    热议问题