import java.util.LinkedList; class SharedResource { private LinkedList buffer = new LinkedList<>(); private int capacity = 2; public void produce() throws InterruptedException { synchronized (this) { while (buffer.size() == capacity) { wait(); } int item = (int) (Math.random() * 100); System.out.println("Produced: " + item); buffer.add(item); notify(); } } public void consume() throws InterruptedException { synchronized (this) { while (buffer.isEmpty()) { wait(); } int item = buffer.removeFirst(); System.out.println("Consumed: " + item); notify(); } } } class Producer extends Thread { private SharedResource sharedResource; public Producer(SharedResource sharedResource) { this.sharedResource = sharedResource; } @Override public void run() { try { while (true) { sharedResource.produce(); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } class Consumer extends Thread { private SharedResource sharedResource; public Consumer(SharedResource sharedResource) { this.sharedResource = sharedResource; } @Override public void run() { try { while (true) { sharedResource.consume(); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class ProducerConsumerExample { public static void main(String[] args) { SharedResource sharedResource = new SharedResource(); Producer producer = new Producer(sharedResource); Consumer consumer = new Consumer(sharedResource); producer.start(); consumer.start(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter