JUC-05-Callable

JUC-05-Callable

1. 简介

mark

  • 可以有返回值
  • 可以抛出异常
  • 方法不同 runnable->run() / callable->call()

2. 代码测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class TestCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {

// Callable无法直接启动,必须要使用FutureTask<V>
// new Thread().start();

MyThread thread = new MyThread();

// Callable必须要适配类
FutureTask futureTask = new FutureTask(thread);
new Thread(futureTask,"A").start();
// 线程结果会被缓存,效率高
new Thread(futureTask,"B").start();

// 拿取返回值
Integer o = (Integer) futureTask.get();
System.out.println(o);
}
}


class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("call()");
return 1024;
}
}
  • 细节
    • 有缓存
    • 结果可能需要等待

下面是关系图,望有助理解

mark

mark

参考博客链接:https://blog.csdn.net/sinat_39634657/article/details/81456810

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信