-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFutureTaskTest.java
More file actions
99 lines (82 loc) · 2.78 KB
/
Copy pathFutureTaskTest.java
File metadata and controls
99 lines (82 loc) · 2.78 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* 也算是另一种的Future模式
* Created by yahier on 17/3/6.
*/
public class FutureTaskTest {
static FutureTask<String> task = new FutureTask<>(new RealData(("a")));
public FutureTaskTest() {
System.out.println("构造函数");
}
static {
FutureTaskTest test = new FutureTaskTest();
}
public static void main(String[] args) {
//ThreadExecute();
//poolExecute();
testTimeout();
}
static void poolExecute() {
ExecutorService executor = Executors.newFixedThreadPool(1);
//Future future = executor.submit(task);
//future.cancel(true);
executor.execute(task);
System.out.println("请求完毕");
try {
for (int i = 0; i < 4; i++) {
Thread.sleep(1000);
if (!task.isCancelled())
System.out.println(i + "数据:" + task.get());//会等待结果
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private static void ThreadExecute() {
new Thread(task).start();
System.out.println("ThreadExecute 请求完毕");
try {
Thread.sleep(1000);
//task.cancel(true);
System.out.println("准备拿结果");//会等待结果
while (!task.isDone()) {
System.out.println("没完成,稍后再来");
Thread.sleep(1000);
}
if (!task.isCancelled())
System.out.println("数据:" + task.get());//会等待结果
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
private static void testTimeout() {
Callable<Integer> call = () -> {
Thread.sleep(180);
return 3;
};
ExecutorService threadPool = Executors.newFixedThreadPool(1);
Future<Integer> future = threadPool.submit(call);
int value = 0;
try {
value = future.get(200, TimeUnit.MILLISECONDS);
System.out.println("value :" + value);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
System.out.println("value:" + value);
}
}