I was trying to understand the CountDownLatch usage, following is the code I am using here,
DecrementRunnable.java
package com.nirjhar.java.countdownlatchexample;
import java.util.concurrent.CountDownLatch;
public class DecrementRunnable implements Runnable {
private String name;
private CountDownLatch cdl;
public DecrementRunnable(String name, CountDownLatch cdl) {
this.name=name;
this.cdl=cdl;
}
@Override
public void run() {
System.out.println("in run method");
for (int i = 0; i < 6; i++) {
cdl.countDown();
System.out.println("counting down "+cdl.getCount());
}
//cdl.notifyAll();
System.out.println("Notified to all");
}
}
CountDownDemoThread.java
package com.nirjhar.java.countdownlatchexample;
import java.util.concurrent.CountDownLatch;
public class CountDownDemoThread extends Thread {
private CountDownLatch cdl;
public CountDownDemoThread(String name, CountDownLatch cdl) {
this.cdl=cdl;
setName(name);
}
@Override
public synchronized void start() {
System.out.println("Task completed ... waiting for other thread to complete their task");
try {
cdl.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Continuing my tasks ..");
}
}
Main Program,
package com.nirjhar.java.countdownlatchexample;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args)
{
CountDownLatch cdl=new CountDownLatch(6);
Thread tDecrementThread=new Thread(new DecrementRunnable("Runnable", cdl));
CountDownDemoThread cddt=new CountDownDemoThread("thread", cdl);
cddt.start();
System.out.println("thread 1 started");
tDecrementThread.start();
}
}
In this main program, i was expecting this line "thread 1 started" should get printed once the thread one is started, But here main thread is blocked because of the wait statement in cdl.await() statement in cddt thread. Just wanted to know what is the reason behind this?