In my program CountDownLatch await () method will continue blocking program, CountDownLatch as it is written, Is a countdown latch, when the count to zero trigger three Thread execution, and prove that three when cdAnswer reduced to 0 Thread has been executed, then the Main Thread to execute, but in my program, three Thread only completes The two Main Thread was carried out, who can help me, I would be very grateful. The bottom is my program.
public class CountdownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("Thread" + Thread.currentThread().getName()
+ "Wait for the command");
cdOrder.await();
System.out.println("Thread" + Thread.currentThread().getName()
+ "received command");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("Thread" + Thread.currentThread().getName()
+ "Feedback the results");
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("To complete the order");
cdAnswer.countDown();
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("Thread" + Thread.currentThread().getName()
+ "The upcoming orders");
cdOrder.countDown();
System.out.println("Thread" + Thread.currentThread().getName()
+ "Sent the command, are waiting for the result");
cdAnswer.await();
System.out.println("Thread" + Thread.currentThread().getName()
+ "Have received all the response. "
+ "The results of this task has been completed");
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}
Problem complement: This result is not what I expected, I thought this sentence ‘Have received all the response. The results of this task has been completed’will be in the final print
This is because if you see run method of your runnable
public void run() {
try {
System.out.println("Thread"
+ Thread.currentThread().getName()
+ "Wait for the command");
cdOrder.await();
System.out.println("Thread"
+ Thread.currentThread().getName()
+ "received command");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("Thread"
+ Thread.currentThread().getName()
+ "Feedback the results");
cdAnswer.countDown(); -- countdown on latch cdAnswer
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("To complete the order");
cdAnswer.countDown(); -- countdown on latch cdAnswer
}
}
cdAnswer.countDown(); is called twice for each runnable one in finally and one before catch clause. So for three threads countdown is called six times as a result main thread starts after 3 countdown.
Remove cdAnswer.countDown(); just above catch statement it work as expected