-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompletionServiceTest1.java
More file actions
62 lines (53 loc) · 1.58 KB
/
Copy pathCompletionServiceTest1.java
File metadata and controls
62 lines (53 loc) · 1.58 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
package four;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author yangxp
* 2019年12月6日上午11:18:39
* <p>描述:completionService.take().get() 返回最快结果的get
*/
public class CompletionServiceTest1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newCachedThreadPool();
CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
completionService.submit(new MyThread01());
completionService.submit(new MyThread02());
executorService.shutdown();
System.out.println(completionService.take().get());
System.out.println(completionService.take().get());
}
}
class MyThread01 implements Callable<String> {
@Override
public String call() {
int sum = 0;
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(200);
sum += i;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(sum + 30000000);
}
}
class MyThread02 implements Callable<String> {
@Override
public String call() {
int sum = 999;
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(400);
sum += i;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(sum + 30000000);
}
}