篮子-水果模拟消费者生产者
package com.iotec.synchronizedTest; import java.util.LinkedList; public class ProductorConsumerDemo { public static void main(String[] args) { Backet backet = new Backet(); Productor productor = new Productor(backet); Consumer consumer = new Consumer(backet); productor.start(); consumer.start(); } } class Productor extends Thread{ private Backet backet = null; public Productor(Backet backet){ super(); this.backet = backet; } @Override public void run() { backet.pushApple(); } } class Consumer extends Thread{ private Backet backet = null; public Consumer(Backet backet){ super(); this.backet = backet; } @Override public void run() { backet.popApple(); } } class Backet{ private LinkedList<Apple> basket = new LinkedList<>(); //放4轮苹果 public synchronized void pushApple(){ for(int i = 0;i<20;i++){ Apple apple = new Apple(i); push(apple); } } public synchronized void popApple(){ for(int i = 0;i<20;i++) { pop(); } } //向篮子放苹果 private void push(Apple apple){ //当篮子中存放了5个苹果就等待并通知消费者来消费 if(basket.size()==5){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }//等待并释放当前对象的锁 } try { //当不满足5个的时候,则每隔500毫秒放一个苹果 Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } basket.addFirst(apple); System.out.println("存放:"+apple.toString()); notify(); //通知消费者来消费 } //向篮子取苹果 private void pop(){ //当篮子中存放了0个苹果就等待并通知生产者来生产 if(basket.size()==0){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }//等待并释放当前对象的锁 } try { //当不满足5个的时候,则每隔500毫秒放一个苹果 Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Apple apple = basket.removeFirst(); System.out.println("吃掉:"+apple.toString()); notify(); //通知生产者生产 } } class Apple{ private int id; public Apple(int id){ this.id = id; } @Override public String toString() { return "Appple:"+(id+1); } }