10. Producer Consumer Problem - prabhatrocks07/Core-Java-Programming GitHub Wiki

public class ProducerConsumerProblem {

public static void main(String[] args) throws InterruptedException{
	PC pc = new PC();
	
	Runnable r1 = () -> {
		try {
			pc.produce();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	};
						
	Runnable r2 = () -> {
		try {
			pc.consume();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	};
	
	Thread t1 = new Thread(r1, "Producer");
	Thread t2 = new Thread(r2, "Consumer");
	
	t1.start();
	t2.start();
	
	t1.join();
	t2.join();
}

}

class PC {
LinkedList<Integer> list = new LinkedList<Integer>();
final static int CAPACITY = 2;

public void produce() throws InterruptedException {
	int value = 0;
	
	while(true){
		synchronized (this) {
			if(list.size() == CAPACITY) {
				wait();
			}
			
			System.out.println("Producer produced : " + value);
			list.add(value++);
			notify();
			Thread.sleep(1000);
		}
	}
}

public void consume() throws InterruptedException {
	while(true){
		synchronized (this) {
			if(list.size() == 0) {
				wait();
			}
			
			int value = list.removeFirst();
			System.out.println("Consumer consumed : " + value);
			notifyAll();
			Thread.sleep(1000);
		}
	}
}
}
⚠️ **GitHub.com Fallback** ⚠️