走近Callable
小于 1 分钟JavaJUC并发编程

- 可以有返回值。
- 可以抛出异常。
- 方法不同。call()方法。
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}

Runnable接口

FutureTask类是Runnable接口的实现类
FutureTask(Callable<V> callable)
Creates a FutureTask that will, upon running, execute the given Callable.

public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThread myThread = new MyThread();
// 适配类 FutureTask
FutureTask futureTask = new FutureTask(myThread);
new Thread(futureTask, "A").start();
// 结果会被缓存,效率高
new Thread(futureTask, "B").start();
// 获取Callable的返回结果.get方法可能会产生阻塞
Integer rst = (Integer) futureTask.get();
// 或者使用异步同信来处理
System.out.println(rst);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("call()");
// 耗时的操作
return 1024;
}
}
结果:
call()
1024
Process finished with exit code 0
- 结果会被缓存,效率高。
- get方法结果可能会等待,产生阻塞。