Discuss / Java / future到底用在什么场景呢?

future到底用在什么场景呢?

Topic source

The__Wolf

#1 Created at ... [Delete] [Delete and Lock User]

看完了没懂什么地方要用到future,哪位大神解释下呢

miro不老

#2 Created at ... [Delete] [Delete and Lock User]

(1)子线程返回类型String,那主线程如何获取子线程中执行结果?

class Task implements Callable<String> {
    public String call() throws Exception {
// 模拟子线程处理任务....
        return longTimeCalculation(); 
    }
}

(2)主线程通过  future.get()获取子线程中返回的数据

Future<String> future = executor.submit(task);
// 从Future获取异步执行返回的结果:
String result = future.get(); // 可能阻塞

fqjx

#3 Created at ... [Delete] [Delete and Lock User]

用在将来(future)某个时候

Loading...

#4 Created at ... [Delete] [Delete and Lock User]

你只执行任务,不接收参数了吗?如果只执行任务不需要接受返回参数,用Runnable接口就可以,不然就要用Callable接口,配合future接到任务执行完返回的参数。

Runnable接口也可以返回Future对象,只不过当执行成果后返回是null.<Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return null upon successful completion.>

Future<?> submit(Runnable task);

  • 1

Reply