ExecutorService.submit(Runnable task,T result)中的’result’是什么做的?
看看javadocs,它只是说
Future submit(Runnable task, T result)
提交Runnable任务以执行并返回表示该任务的Future。 Future的get方法将在成功完成后返回给定的结果。
参数:
任务 – 要提交的任务
结果 – 返回的结果
但它对结果有什么作用? 它存储了什么吗? 它只是使用结果类型来指定Future
的类型吗?
它对结果没有任何作用 – 只是持有它。 任务成功完成后,调用future.get()
将返回您传入的结果。
以下是Executors $ RunnableAdapter的源代码,它显示在任务运行后,返回原始结果:
static final class RunnableAdapter implements Callable { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } }
是的,结果的generics类型应该与返回的Future的类型相匹配。
Runnable不会返回任何内容,Future必须返回一些内容,因此此方法允许您预定义返回的未来的结果。
如果你不想返回一个东西,你可以返回null,我认为Void
类型存在来表达那种东西。
Future myFuture = executor.submit(myTask, null);
你知道myFuture.get()
在这种情况下会返回null
,但只有在任务运行之后才会返回null
,所以你会用它来等待并抛出任务中抛出的任何exception。
try { myFuture.get(); // After task is executed successfully ... } catch (ExecutionException e) { Throwable c = e.getCause(); log.error("Something happened running task", c); // After task is aborted by exception ... }
您可以改变在任务期间传入的对象。 例如:
final String[] mutable = new String[1]; Runnable r = new Runnable() { public void run() { mutable[0] = "howdy"; } }; Future f = executorService.submit(r, mutable); String[] result = f.get(); System.out.println("result[0]: " + result[0]);
当我运行此代码时,它输出:
result[0]: howdy