-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCountDownLatchDemo.java
More file actions
52 lines (42 loc) · 1.45 KB
/
Copy pathCountDownLatchDemo.java
File metadata and controls
52 lines (42 loc) · 1.45 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
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchDemo{
final static int NTHREADS = 3;
public static void main(String[] args){
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch doneSignal = new CountDownLatch(NTHREADS);
Runnable runnable = new Runnable(){
@Override
public void run(){
try{
report("entered run()");
startSignal.await(); // wait until count down to zero.
report("doing work");
Thread.sleep((int)(Math.random()*10000));
doneSignal.countDown(); // decrement the count if not zero
}catch(InterruptedException ie){
System.err.println(ie);
}
}
void report(String s){
System.out.println(System.currentTimeMillis() + ": " + Thread.currentThread() + ": " + s);
}
};
ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
for(int i=0; i<NTHREADS; i++){
executor.execute(runnable);
}
try{
System.out.println("main thread doing something");
Thread.sleep(1000);
startSignal.countDown();
System.out.println("main thread doing something else");
doneSignal.await(); // wait till count down to be zero. main thread is waiting for the end.
executor.shutdownNow();
System.out.println("main thread's wait finished. That's the end.");
}catch(InterruptedException ie){
System.err.println(ie);
}
}
}