/** * 生产者/消费者问题 */ class Clerk{//产品 private int productNumber=0; public synchronized void produceProduct(){ if (productNumber<20){ productNumber++; System.out.println(Thread.currentThread().getName()+"开始生产第:"+productNumber+"件产品"); notify(); }else { //等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void customerProduct(){ if (productNumber>0){ notify(); System.out.println(Thread.currentThread().getName()+"开始消费第:"+productNumber+"件产品"); productNumber--; 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("生产者开始生产产品。。。"); while (true){ try { 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("消费者开始消费产品。。。"); while (true){ try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } clerk.customerProduct(); } } } public class ProductTest { public static void main(String[] args) { Clerk clerk=new Clerk(); Producer p1=new Producer(clerk); Customer c1=new Customer(clerk); p1.setName("生产者"); c1.setName("消费者"); p1.start(); c1.start(); } }