-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCallableTest.java
More file actions
41 lines (34 loc) · 996 Bytes
/
CallableTest.java
File metadata and controls
41 lines (34 loc) · 996 Bytes
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
29
30
31
32
33
34
35
36
37
38
39
40
41
package org.cp;
import java.util.concurrent.*;
/**
* Callable初体验
* create by CP on 2019/7/29 0029.
*/
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CC cc = new CC();
FutureTask task = new FutureTask(cc);//封装Callable实现类
Thread thread = new Thread(task);
thread.start();
Object o = task.get();//阻塞式获取
System.out.println(o);
try {
Object o1 = task.get(1, TimeUnit.SECONDS);//阻塞式获取
System.out.println(o1);
} catch (TimeoutException e) {
System.out.println("1 秒后,没取到结果");
e.printStackTrace();
}
}
}
class CC implements Callable {
@Override
public Object call() throws Exception {
Integer sum = 0;
for (int i = 0; i <= 100; i++) {
sum+=i;
}
Thread.sleep(5000);
return sum;
}
}