如何让Callable等到执行?

mil*_*_db 0 java multithreading callable task

我有一个Callable,我调用了它

FutureTask<Integer> task = new FutureTask<Integer>(new MyCallable(name, type));
pool = Executors.newSingleThreadExecutor();
pool.submit(task);
Run Code Online (Sandbox Code Playgroud)

我想知道执行是继续执行pool.submit(task)还是等待可调用来完成执行?

总之我只是想知道有没有像thread.join()Callable 这样的方法?

Gra*_*ray 11

...对于Callable,有没有像thread.join()这样的方法?

如果线程在池中可用,则该pool.submit(callable)方法返回a Future并立即开始执行.要执行a join,您可以调用future.get()与线程的连接,返回call()方法返回的值.重要的是要注意,如果方法投掷,get()可能抛出一个.ExecutionExceptioncall()

不需要包装你CallableFutureTask.线程池为您做到了这一点.所以你的代码是:

pool = Executors.newSingleThreadExecutor();
Future<String> future = pool.submit(new MyCallable(name, type));

// now you can do something in the foreground as your callable runs in the back

// when you are ready to get the background task's result you call get()
// get() waits for the callable to return with the value from call
// it also may throw an exception if the call() method threw
String value = future.get();
Run Code Online (Sandbox Code Playgroud)

这是你的MyCallable工具Callable<String>当然.该Future<?>会匹配任何类型你Callable是.