Repository navigation
Expand file tree
/
Copy pathSimpExec.java
More file actions
60 lines (48 loc) · 1.54 KB
/
Copy pathSimpExec.java
File metadata and controls
60 lines (48 loc) · 1.54 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
//listing 6
// A simple example that uses an Executor.
import java.util.concurrent.*;
class SimpExec {
public static void main(String args[]) {
long start = System.currentTimeMillis();
CountDownLatch cdl1 = new CountDownLatch(500000);
CountDownLatch cdl2 = new CountDownLatch(500000);
CountDownLatch cdl3 = new CountDownLatch(500000);
CountDownLatch cdl4 = new CountDownLatch(500000);
ExecutorService es = Executors.newFixedThreadPool(4);
//ExecutorService es = Executors.newCachedThreadPool();
System.out.println("Starting");
// Start the threads.
es.execute(new MyThread(cdl1, "A"));
es.execute(new MyThread(cdl2, "B"));
es.execute(new MyThread(cdl3, "C"));
es.execute(new MyThread(cdl4, "D"));
try {
cdl1.await();
cdl2.await();
cdl3.await();
cdl4.await();
} catch (InterruptedException exc) {
System.out.println(exc);
}
if (!es.isTerminated())
es.shutdown();
System.out.println("Done");
long end = System.currentTimeMillis();
System.out.println(end-start);
}
}
class MyThread implements Runnable {
String name;
CountDownLatch latch;
MyThread(CountDownLatch c, String n) {
latch = c;
name = n;
new Thread(this);
}
public void run() {
for (int i = 0; i < 500000; i++) {
System.out.println(name + ": " + i);
latch.countDown();
}
}
}