forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountDownLatchExample.java
More file actions
45 lines (36 loc) · 1.06 KB
/
CountDownLatchExample.java
File metadata and controls
45 lines (36 loc) · 1.06 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
package multithreading;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
Worker first = new Worker(1000, latch, "WORKER-1");
Worker second = new Worker(2000, latch, "WORKER-2");
Worker third = new Worker(3000, latch, "WORKER-3");
Worker fourth = new Worker(4000, latch, "WORKER-4");
first.start();
second.start();
third.start();
fourth.start();
latch.wait(); // The main task waits for four threads
System.out.println(Thread.currentThread().getName() + " has finised");
}
}
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() + " finished");
} catch (Exception e) {
e.printStackTrace();
}
}
}