Here is an example of producer-consumer problem using CyclicBarrier in Java:
import java.util.concurrent.CyclicBarrier;
class ProducerConsumer {
public static void main(String[] args) {
int numProducers = 5;
int numConsumers = 5;
CyclicBarrier barrier = new CyclicBarrier(numProducers + numConsumers);
// Start the producers
for (int i = 0; i < numProducers; i++) {
new Thread(new Producer(barrier)).start();
}
// Start the consumers
for (int i = 0; i < numConsumers; i++) {
new Thread(new Consumer(barrier)).start();
}
}
}
class Producer implements Runnable {
private CyclicBarrier barrier;
public Producer(CyclicBarrier barrier) {
this.barrier = barrier;
}
public void run() {
System.out.println("Producer started producing...");
try {
// Wait for other threads to finish
barrier.await();
System.out.println("Producer finished producing");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
private CyclicBarrier barrier;
public Consumer(CyclicBarrier barrier) {
this.barrier = barrier;
}
public void run() {
System.out.println("Consumer started consuming...");
try {
// Wait for other threads to finish
barrier.await();
System.out.println("Consumer finished consuming");
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, we have created a CyclicBarrier object with numProducers + numConsumers parties. This means that the barrier.await() method will not proceed until all the producers and consumers have finished their operations.
The producer and consumer threads are started, and they run their operations. Once they have finished, they call the barrier.await() method, which waits for all the threads to reach the same point before continuing. This way, we ensure that all the producers have finished producing and all the consumers have finished consuming before proceeding with any other operations.
No comments:
Post a Comment