线程 生产者 消费者 例题
package com.cj.java1; class Producer extends Thread{ private Clerk clerk; public Producer(Clerk clerk){ this.clerk = clerk; } @Override public void run() { System.out.println("开始生产"); while (true){ try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } clerk.addProduct(); } } } class Clerk{ private int productCount = 0; public synchronized void addProduct() { if (productCount<20){ productCount++; System.out.println(Thread.currentThread().getName() + "开始生产第:"+productCount+"个产品"); notify(); }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void decProduct() { if (productCount>0){ System.out.println(Thread.currentThread().getName() + "开始消费第:"+productCount+"个产品"); productCount--; notify(); }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Customer extends Thread{ private Clerk clerk; public Customer(Clerk clerk){ this.clerk = clerk; } @Override public void run() { System.out.println("开始消费"); while (true){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } clerk.decProduct(); } } } public class ProductTest { public static void main(String[] args) { Clerk clerk = new Clerk(); Producer producer = new Producer(clerk); Customer customer = new Customer(clerk); producer.setName("生产者"); customer.setName("消费者"); producer.start(); customer.start(); } }