Created
January 22, 2024 04:26
-
-
Save camilajenny/960a21d838cef2e65788d57105abe650 to your computer and use it in GitHub Desktop.
Example usage of CountDownLatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: