I am writing a simple program to demonstrate CountDownLatch
. Here is my program:
class Players implements Runnable {
private int delay;
private String name;
private CountDownLatch latch;
Players(int delay, String name, CountDownLatch latch) {
this.delay = delay;
this.name = name;
this.latch = latch;
}
@Override
public void run() {
System.out.println("Player" + name + "joined");
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
public class LudoDemoUsingCountDownLatch {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(4);
ExecutorService service = Executors.newFixedThreadPool(4);
service.execute(new Players(11000, "player-1", latch));
service.execute(new Players(12000, "player-2", latch));
service.execute(new Players(13000, "player-3", latch));
service.execute(new Players(14000, "player-4", latch));
try {
latch.await(1000, TimeUnit.MILLISECONDS);
System.out.println("All four playesr joined. game started ");
} catch (InterruptedException e) {
System.out.println("cant start the game ");
}
}
}
I am expecting that main thread should kick in even before any player is joining and code inside catch block should execute as the waiting time for await method is less than the sleep method of all players threads. But I am not getting that output. Instead, it is showing that all players joined and the game was started:
output:
1. Player-2joined
2. Player-3joined
3. Player-1joined
4. Player-4joined
5. All four players joined. game started
You need to check the return value of CountDownLatch.await
. It doesn't throw InterruptedException
when it times out; it returns false
.
So, a corrected version of your main
method would look like:
CountDownLatch latch = new CountDownLatch(4);
ExecutorService service = Executors.newFixedThreadPool(4);
service.execute(new Players(11000, "player-1", latch));
service.execute(new Players(12000, "player-2", latch));
service.execute(new Players(13000, "player-3", latch));
service.execute(new Players(14000, "player-4", latch));
boolean started = false;
try {
started = latch.await(1000, TimeUnit.MILLISECONDS);
if (started) {
System.out.println("All four players joined. game started ");
}
} catch (InterruptedException e) {
System.out.println("Interrupted - won't generally be hit");
}
if (!started) {
System.out.println("Can't start the game");
}
Note that you probably also meant to put System.out.println("Player" + name + "joined");
after the Thread.sleep
call in Player
.