Whi*_*cal 5 multithreading java.util.concurrent java-8 concurrent.futures
FutureTask 包装器比简单的 Callable/Runnables 提供什么?我见过一些人以这种方式使用 future,但我不确定它到底给游戏带来了什么。
Callable<Integer> myComputation = () -> {return 0;};
FutureTask<Integer> task = new FutureTask<Integer>(myComputation);
//Why this...
Executors.newSingleThreadExecutor().execute(task);
task.get();
//...over the conventional approach?
Future<Integer> future = Executors.newSingleThreadExecutor().submit(myComputation);
future.get();
Run Code Online (Sandbox Code Playgroud)
我看不出有什么好处。公共接口的唯一区别是,除了方法之外,FutureTask
实现还允许您通过方法运行任务,但我怀疑您是否需要直接运行它。RunnableFuture
Future
RunnableFuture.run()
直接使用该类的主要目的FutureTask
是能够对其进行子类化,为某些受保护的方法(如done()
或 )提供自定义实现setException()
。所以下面的代码是有意义的:
Callable<Integer> myComputation = () -> {return 0;};
FutureTask<Integer> task = new FutureTask<Integer>(myComputation) {
@Override
protected void done() {
// some custom action on task completion
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1474 次 |
最近记录: |