一个生产者,消费者的例子:
import java.util.Stack; /** * Created by root on 17-10-1. */ public class Test5 { //商品:APPLE class Apple { private int id; public Apple(int id) { this.id = id; } @Override public String toString() { return "Apple{" + "id=" + id + '}'; } } //存放商品的仓库 class Repositorie { Stack<Apple> capacity = new Stack<>(); int MAXSIZE = 10; public synchronized void putApple(Apple apple) throws InterruptedException { if (capacity.size() < MAXSIZE) { capacity.push(apple); System.out.println(Thread.currentThread().getName()+"生产Apple>>>" + apple.toString()); notify(); } else { wait(); } } public synchronized void getApple() throws InterruptedException { if (capacity.size() > 0) { System.out.println(" "+Thread.currentThread().getName()+"消费Apple<<<" + capacity.pop().toString()); notify(); } else { wait(); } } public void close(){ while (true){ //卖完了就打烊 if (capacity.size()==0){ System.exit(0); } } } } //生产者 class Producer implements Runnable { int NUM=20;//一共生产20个商品 private Repositorie repositorie; public Producer(Repositorie repositorie) { this.repositorie = repositorie; } @Override public void run() { for (; NUM>0; ) { try { repositorie.putApple(new Apple(NUM--)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } repositorie.close(); } } //消费者 class Consume implements Runnable { private Repositorie repositorie; public Consume(Repositorie repositorie) { this.repositorie = repositorie; } @Override public void run() { //不知道有多少商品 for (;true;) { try { repositorie.getApple(); Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Test5 test5 = new Test5(); Repositorie repositorie = test5.new Repositorie(); Producer producer = test5.new Producer(repositorie); Consume consume = test5.new Consume(repositorie); Thread p1 = new Thread(producer,"工人1"); Thread p2 = new Thread(producer,"工人2"); Thread c1 = new Thread(consume,"客户1"); Thread c2 = new Thread(consume,"客户2"); p1.start(); p2.start(); c1.start(); c2.start(); } }
结果:
工人1生产Apple>>>Apple{id=20} 工人2生产Apple>>>Apple{id=19} 客户2消费Apple<<<Apple{id=19} 客户1消费Apple<<<Apple{id=20} 工人1生产Apple>>>Apple{id=18} 工人2生产Apple>>>Apple{id=17} 工人1生产Apple>>>Apple{id=16} 工人2生产Apple>>>Apple{id=15} 工人1生产Apple>>>Apple{id=14} 客户1消费Apple<<<Apple{id=14} 客户2消费Apple<<<Apple{id=15} 工人2生产Apple>>>Apple{id=13} 工人1生产Apple>>>Apple{id=12} 工人2生产Apple>>>Apple{id=11} 工人1生产Apple>>>Apple{id=10} 工人2生产Apple>>>Apple{id=9} 工人1生产Apple>>>Apple{id=8} 客户1消费Apple<<<Apple{id=8} 客户2消费Apple<<<Apple{id=9} 工人2生产Apple>>>Apple{id=7} 工人1生产Apple>>>Apple{id=6} 工人2生产Apple>>>Apple{id=5} 客户1消费Apple<<<Apple{id=5} 客户2消费Apple<<<Apple{id=6} 工人1生产Apple>>>Apple{id=2} 工人2生产Apple>>>Apple{id=1} 客户1消费Apple<<<Apple{id=1} 客户2消费Apple<<<Apple{id=2} 客户1消费Apple<<<Apple{id=7} 客户2消费Apple<<<Apple{id=10} 客户1消费Apple<<<Apple{id=11} 客户2消费Apple<<<Apple{id=12} 客户1消费Apple<<<Apple{id=13} 客户2消费Apple<<<Apple{id=16} 客户1消费Apple<<<Apple{id=17} 客户2消费Apple<<<Apple{id=18}