Callable
- 可以有返回值
- 可以抛出异常
- 方法 call()
public class CallableTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyCallable myCallable = new MyCallable();
FutureTask task = new FutureTask<>(myCallable);
new Thread(task, "tname1").start();
new Thread(task, "tname2").start(); // 结果会被缓存,多次调用call方法只执行一次
// 获取callable返回结果 get方法可能产生阻塞
String str = (String) task.get();
System.out.println(str);
}
}
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("call runs..");
return "hello world";
}
}
image.png
网友评论