package countdownlatchTest;
import java.util.concurrent.CountDownLatch;
class Worker {
private String name;
private long workDuration;
public Worker(String name, long workDuration) {
this.name = name;
this.workDuration = workDuration;
System.out.println("Worker: " + name + " is assigned with work time: " + workDuration);
}
public void doWork() {
System.out.println(name + " begins to work...");
try {
Thread.sleep(workDuration);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(name + " has finished the job...");
}
}
class WorkerTestThread implements Runnable {
private Worker worker;
private CountDownLatch cdLatch;
public WorkerTestThread(Worker worker, CountDownLatch cdLatch) {
this.worker = worker;
this.cdLatch = cdLatch;
}
@Override
public void run() {
worker.doWork();
cdLatch.countDown();
}
}
public class CountDownLatchTest {
private static final int MAX_WORK_DURATION = 5000;
private static final int MIN_WORK_DURATION = 1000;
private static long getRandomWorkDuration(long min, long max) {
return (long) (Math.random() * (max - min) + min);
}
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(2);
Worker w1 = new Worker("Jerry Worker 1", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));
Worker w2 = new Worker("Jerry Worker 2", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));
new Thread(new WorkerTestThread(w1, latch)).start();
new Thread(new WorkerTestThread(w2, latch)).start();
try {
latch.await();
System.out.println("All jobs have been finished!");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}