Skip to content

Instantly share code, notes, and snippets.

@njofce
Created March 24, 2020 17:39
Show Gist options
  • Save njofce/717be0b92eef075c195cbcef6c043f71 to your computer and use it in GitHub Desktop.
Save njofce/717be0b92eef075c195cbcef6c043f71 to your computer and use it in GitHub Desktop.
class Producer extends Thread{
public String producerName;
Buffer<String> buffer;
public Producer(String name, Buffer<String> buffer) {
this.producerName = name;
this.buffer = buffer;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(producerName + " produces item " + i);
try {
buffer.addItem(i + " produced by: " + producerName);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread{
public String consumerName;
Buffer<String> buffer;
public Consumer(String name, Buffer<String> buffer) {
this.consumerName = name;
this.buffer = buffer;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
String item = null;
try {
item = buffer.getItem();
System.out.println("The item \"" + item + "\" consumed by " + consumerName);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Sync {
public static void main(String[] args) throws InterruptedException {
Buffer<String> buffer = new Buffer<>(5);
HashSet<Thread> producers = new HashSet<>();
HashSet<Thread> consumers = new HashSet<>();
for(int i = 0; i < 10; i++) {
producers.add(new Producer("Producer"+i, buffer));
consumers.add(new Consumer("Consumer"+i, buffer));
}
consumers.forEach(Thread::start);
producers.forEach(Thread::start);
for (Thread producer : producers) {
producer.join();
}
for (Thread consumer : consumers) {
consumer.join();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment