-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountDownLatchExample.java
More file actions
49 lines (43 loc) · 1.58 KB
/
CountDownLatchExample.java
File metadata and controls
49 lines (43 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
public class CountDownLatchExample {
public static void main(String args[]) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
Worker thread1 = new Worker(2000, latch, "Worker Thread-1");
Worker thread2 = new Worker(3000, latch, "Worker Thread-2");
Worker thread3 = new Worker(1000, latch, "Worker Thread-3");
Worker thread4 = new Worker(4000, latch, "Worker Thread-4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
System.out.println("Main thread is here");
latch.await();
System.out.println("Thread "+Thread.currentThread().getName()+" has finished");
/* <-------- Console -------->
Main thread is here
Worker Thread-3 has finished
Worker Thread-1 has finished
Worker Thread-2 has finished
Worker Thread-4 has finished
main has finished
*/
}
}
class Worker extends Thread {
private int delay;
private CountDownLatch latch;
public Worker(int delay, CountDownLatch latch, String name) {
super(name);
this.delay = delay;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(delay);
latch.countDown();
System.out.println(Thread.currentThread().getName() + " has finished");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}