/** * 单生产者单消费者 * 一个生产线成一个消费线程 * 一个生产任务一个消费任务 * 一个产品 */ public class Demo5 { public static void main(String[] args) {
//产品类的对象 P p = new P(); //创建任务类的对象 Producer producer3 = new Producer(p); Consumer consumer3 = new Consumer(p); //创建线程 Thread t0 = new Thread(producer3); Thread t1 = new Thread(consumer3); //开启线程 t0.start(); t1.start(); } } //产品类 class P {
//产品类的属性:名字、价格、产品数量 String name; double price; int count;
//标识 boolean flag = false; //负责生产 public synchronized void setP(String name, double price) { if (flag == true) { try { wait(); //让生产线等待 } catch (InterruptedException e) { e.printStackTrace(); } } this.name = name; this.price = price; System.out.println(Thread.currentThread().getName() +" 生产了:"+this.name +" 产品数量:"+ this.count +" 产品价格:"+ this.price); count++; flag = ! flag; notify(); //唤醒消费线程 } //负责消费 public synchronized void getP() { if(flag == false) { try { wait(); //让消费线程等待 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() +" 消费了:"+this.name +" 产品数量:"+ this.count +" 产品价格:"+ this.price); flag = !flag; notify(); //唤醒生产线程 } } //生产线程 class Producer implements Runnable{ P p; public Producer(P p) { this.p = p; } @Override public void run() { while(true) { p.setP("冰冰", 20); } } } //消费线程 class Consumer implements Runnable{ P p; public Consumer(P p) { this.p = p; } @Override public void run() { while(true) { p.getP(); } } }