java.util.concurrent.FutureTask 如果阻塞 main 有什么用?

What is the use of java.util.concurrent.FutureTask if it blocks main?

我对学习比较陌生java.util.concurrent。在实现一个基本程序(如下)时,很明显主线程等待 Callable 到 return 一个值。

    public class FutureTaskTutorial {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask(new MyCallable());
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
        System.out.println("main thread done!");
    }
}

class MyCallable implements Callable<String>{

    @Override
    public String call() throws Exception {
        Thread.sleep(5000);
        return "Callable task done!";
    }
}

输出: <5 秒后>

可调用任务完成!

主线程完成!

我的问题是:如果我的可调用对象将阻塞主线程并且不会实现异步行为,那么使用 FutureTask 有什么意义?

FutureTask#get 可能会阻塞,但是 FutureTasks 的用例是定期检查它们是否完成,同时仍在执行 main-method 的其余部分。例如:

FutureTask<Object> task = new FutureTask<>( () ->
{
  Thread.sleep( 1_000 );
  return "Hello world";
} );

Executors.newSingleThreadExecutor().execute( task );

boolean doMainWork = true;

while( doMainWork )
{
  if( task.isDone() )
  {
    System.out.println( task.get() );
    doMainWork = false;
  }
  System.out.println( "Main working " + task.isDone() );
  Thread.sleep( 500 );
}