-
-
Save njofce/717be0b92eef075c195cbcef6c043f71 to your computer and use it in GitHub Desktop.
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
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