forked from dangtuanhuy/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPoolDemo.java
More file actions
91 lines (86 loc) · 2.82 KB
/
Copy pathThreadPoolDemo.java
File metadata and controls
91 lines (86 loc) · 2.82 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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Session8_ThreadPool;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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;
/**
*
* @author lhhuong
*/
public class ThreadPoolDemo {
private static boolean isError = false;
public static void main(String[] args){
ExecutorService exec = Executors.newFixedThreadPool(2);
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 100; i++) {
if(isError)
break;
System.out.println("Thread 1: "+i);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
return "Task 1";
}
});
callables.add(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 2; i++) {
if(isError)
break;
int a = 3/0;
System.out.println("Thread 2: "+i);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
return "Task 2";
}
});
callables.add(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
if(isError)
break;
System.out.println("Thread 3: "+i);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
return "Task 3";
}
});
try {
List<Future<String>> futures = exec.invokeAll(callables);
for (Future<String> future : futures) {
System.out.println("future.get = "+future.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
catch(ExecutionException ex){
ex.printStackTrace();
}
exec.shutdown();
}
}