Version: Next

Callable

多线程的第三种创建方式

  • 可以有返回值
  • 可以抛出异常
  • 支持泛型
  • 方法不同 run() / call()
  • Thread能接收Runnable
  • Callable无法直接启动,为了整到Thread上,需要找Runnable
  • Runnable有一些默认的实现类:FutureTask
  • FutureTask可以接收Callable参数:FutureTask(Callable<V> callable)
public class Demo04Callable2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new myCallable());
new Thread(futureTask).start();
Integer result = (Integer) futureTask.get();
System.out.println(result);
}
}
class myCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("call method");
return 123;
}
}
call method
123

缓存

  • 开两个线程,使用同一个FutureTask,只会执行一次call方法
  • 因为它有缓存
  • 结果可能需要等待,会阻塞
public class Demo04Callable2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new myCallable());
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start();
Integer result = (Integer) futureTask.get();
System.out.println(result);
}
}
class myCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("call method");
return 123;
}
}
call method
123