阅读:2889回复:0

Callable

楼主#
更多 发布于:2021-02-26 15:50
在开发时耗时的操作都会放到新线程中操作。


如果某个参数在新线程中赋值后,再在原线程中调用。这时如果简单使用runnable,就会发现runnable还没执行完就在原线程中使用了,参数并没有同步过来。


这种情况可以使用Callable接口。
具体方法,以int参数为例:

int result = 0;

Future<Integer> callableFuture  = Executors.newSingleThreadExecutor().submit(new Callable<Integer>(){ @Override public Integer call() throws Exception {

//TODO: your operations


return Integer.valueOf(num); }
})
; try { result = callableFuture.get(); } catch (ExecutionException) {

    e.printTrace();

}
游客

返回顶部