java wait/notify 生产者消费模式

来源:互联网 发布:软件接口是什么 编辑:程序博客网 时间:2024/04/28 06:31
本程序模拟了 一个厨师生产 两个吃货消费的场景
/** * Date:2016年9月7日下午7:56:03 * Copyright (c) 2016, www.bwbroad.com All Rights Reserved. * */package test.wait;import java.util.LinkedList;import java.util.Queue;import java.util.Random;/** * Description: TODO <br/> * Date: 2016年9月7日 下午7:56:03 <br/> *  * @author xuejianxin */public class WaitTest2 {public static int CHUSHI=6;public static int CHIHUO=10;public static void main(String[] args) throws Exception {System.out.println(new Random().nextInt(10));Panzi panzi = new Panzi(2);Chushi chushi = new Chushi("厨师", panzi);chushi.start();Chushi chushi1 = new Chushi("厨师1", panzi);chushi1.start();Chihuo chihuo1 = new Chihuo("吃货1", panzi);Chihuo chihuo2 = new Chihuo("吃货2", panzi);chihuo1.start();chihuo2.start();}public static class Panzi {private int count = 0;private Queue<String> foods;public Panzi(int count) {this.count = count;foods = new LinkedList<String>();}public synchronized void put(String name,String food) {while (foods.size() >= count) {//满了,  这里必须用循环System.out.printf("%d/%d,%s 快吃啊...........................\r\n",foods.size(),this.count,name);try {this.wait();//为什么是 this.wait 是盘子在 wait 吗?????} catch (InterruptedException e) {e.printStackTrace();}}foods.offer(food);System.out.printf("%d/%d,%s----->%s\r\n",foods.size(),this.count,name,food);this.notifyAll();}public synchronized String get(String name) {while (foods.size() == 0) {//这里必须用循环System.out.printf("%d/%d,%s 我等待花儿都谢了...\r\n",foods.size(),this.count,name);try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}String food = foods.poll();System.out.printf("%d/%d,%s******>%s\r\n",foods.size(),this.count,name,food);this.notifyAll();return food;}}// 厨师类public static class Chushi extends Thread {private Panzi panzi;private String name;public Chushi(String name, Panzi panzi) {this.name = name;this.panzi = panzi;}@Overridepublic void run() {int i = 1;String s;while (true) {s = "food" + (i++);//生产一个panzi.put(this.name,s);i++;try {Thread.sleep(new Random().nextInt(CHUSHI)*100);} catch (InterruptedException e) {e.printStackTrace();}}}}// 吃货类public static class Chihuo extends Thread {private String name;private Panzi panzi;public Chihuo(String name, Panzi panzi) {this.name = name;this.panzi = panzi;}@Overridepublic void run() {while (true) {panzi.get(this.name);try {Thread.sleep(new Random().nextInt(CHIHUO)*100);} catch (InterruptedException e) {e.printStackTrace();}}}}}

0 0