Skip to content

Instantly share code, notes, and snippets.

@banan314
Created January 22, 2024 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save banan314/960a21d838cef2e65788d57105abe650 to your computer and use it in GitHub Desktop.
Save banan314/960a21d838cef2e65788d57105abe650 to your computer and use it in GitHub Desktop.
Example usage of CountDownLatch
import java.util.concurrent.CountDownLatch;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
class Participant implements Runnable {
private final CountDownLatch latch;
private final Random random = new Random();
private long id;
private static final Logger LOGGER = Logger.getLogger(Participant.class.getName());
public Participant(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
// Simulate the time taken for the participant to join
try {
Thread.sleep(random.nextLong(10000));
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e.getStackTrace());
Thread.currentThread().interrupt();
}
// Signal that the participant has joined
latch.countDown();
System.out.println("Participant " + id + " has joined the conference.");
}
public void setId(long id) {
this.id = id;
}
}
public class VideoConference {
private static final Logger LOGGER = Logger.getLogger(VideoConference.class.getName());
public static void main(String[] args) {
// Define the number of participants
int numberOfParticipants = 5;
// Create a CountDownLatch with the number of participants
CountDownLatch latch = new CountDownLatch(numberOfParticipants);
// Create participant threads and start them
for (int i = 0; i < numberOfParticipants; i++) {
var participant = new Participant(latch);
var thread = new Thread(participant);
participant.setId(thread.threadId());
thread.start();
}
try {
// Wait for all participants to join
latch.await();
System.out.println("All participants have joined. The meeting has started!");
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e.getStackTrace());
Thread.currentThread().interrupt();
}
}
}
@banan314
Copy link
Author

Output:

Participant 34 has joined the conference.
Participant 33 has joined the conference.
Participant 31 has joined the conference.
Participant 30 has joined the conference.
Participant 32 has joined the conference.
All participants have joined. The meeting has started!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment