Hi friends, Here I am attching the Simple CountDownLatch Java Example, Which will give you idea about how to create the multiple thread and manage them using the CountDownLatch API. the Simple CountDownLatch Java Example will give you idea for CountDownLatch API and usages.

Player.java

package com.javatraineronline.example;
import java.util.concurrent.CountDownLatch;
public class Player implements Runnable {
private CountDownLatch countDownLatch;
private String playerName;
private long duration;
public Player(CountDownLatch countDownLatch, String playName, long duration) {
this.countDownLatch = countDownLatch;
this.playerName = playName;
this.duration = duration;
}
@Override
public void run() {
try {
// Delaying the each thread based on the duration.
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(playerName+" Joined...");
// Counting the each thread.
countDownLatch.countDown();
}
}

CountDownLatchesExample.java

package com.javatraineronline.example;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchesExample {
public static void main(String[] args) {
// Defining the CountDownLatch Object with number of parties
CountDownLatch countDownLatch = new CountDownLatch(3);
// Creating the Players thread.
Thread player1 = new Thread(new Player(countDownLatch, "John", 3000));
player1.setName("John");
Thread player2 = new Thread(new Player(countDownLatch, "William", 5000));
player2.setName("William");
Thread player3 = new Thread(new Player(countDownLatch, "James", 10000));
player3.setName("James");
// Starting all the player threads
player1.start();
player2.start();
player3.start();
System.out.println("Waiting all Player to Join the Game.");
try {
// Waiting all players to join the game
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All Players are Joined.. Game is Started!!!");
}
}

Ouput

[su_box title=”Output for CountDownLatchesExample.java”]Waiting all Player to Join the Game.
John Joined…
William Joined…
James Joined…
All Players are Joined.. Game is Started!!!
[/su_box]

Tags:

One response

Leave a Reply

Your email address will not be published. Required fields are marked *