class ProducerConsumer { private int limit = 5; private int tmp = 0; private int n = 0; private int m = 0; public void produce() throws InterruptedException { int value = 0; while (n++ < limit * 2) { synchronized (this) { while (tmp == limit) { wait(); } System.out.println("Producer produced: " + tmp++); notify(); } } } public void consume() throws InterruptedException { while (m++ < limit * 2) { synchronized (this) { while (tmp == 0) { wait(); } System.out.println("Consumer consumed: " + --tmp); notify(); } } } } public class P4 { public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); Thread producerThread = new Thread(() -> { try { pc.produce(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumerThread = new Thread(() -> { try { pc.consume(); } catch (InterruptedException e) { e.printStackTrace(); } }); producerThread.start(); consumerThread.start(); } }