package java1; /** *OS中经典问题之消费者-生产者同步问题 * @author: Jerry Jin * @Email: jerry20200717@163.com * @version: 1.0.1 * @date: 2021-10-07-17:44 */ class Clerk{ private int productCount = 0; public synchronized void produceProduct() { if (productCount<20){ productCount++; notify(); System.out.println(Thread.currentThread().getName()+ " 开始生产第 "+productCount+" 产品。。。"); }else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void comsumeProduct() { if (productCount>0){ System.out.println(Thread.currentThread().getName()+ " 开始消费第 "+productCount+" 产品。。。"); productCount--; notify(); }else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Producer extends Thread{ private Clerk clerk; public Producer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { System.out.println(Thread.currentThread().getName()+ " :开始生产。。。"); while (true){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } clerk.produceProduct(); } } } class Customer extends Thread{ private Clerk clerk; public Customer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { System.out.println(Thread.currentThread().getName()+ " :开始消费。。。"); while (true){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } clerk.comsumeProduct(); } } } public class ProductTest { public static void main(String[] args) { Clerk clerk = new Clerk(); Producer p1 = new Producer(clerk); Producer p2 = new Producer(clerk); p1.setName("生产者1"); p2.setName("生产者2"); p1.start(); p2.start(); Customer c1 = new Customer(clerk); Customer c2 = new Customer(clerk); c1.setName("消费者1"); c2.setName("消费者2"); c1.start(); c2.start(); } }