马老师的WoTou生产消费线程讲解例子
2016-05-09 15:16
337 查看
public class ProducerConsumer { public static void main(String[] args) { SyncStack ss = new SyncStack(); Producer p = new Producer(ss); Consumer c = new Consumer(ss); new Thread(p).start(); new Thread(p).start(); new Thread(p).start(); new Thread(c).start(); } } //定义一个WoTou类,在类中有id以标记是哪个窝头,重写了toString方法 class WoTou { int id; WoTou(int id) { this.id = id; } public String toString() { return "WoTou : " + id; } } //定义一个篮子的对象,用于装WoTou,在类中有push方法,用于装WoTou,pop方法,用于吃WoTou class SyncStack { int index = 0; WoTou[] arrWT = new WoTou[6]; /* *wate()只有在锁定(synchronized)的时候才能使用 */ //push用于装WoTou,当WoTou数达到6时wait()休息 public synchronized void push(WoTou wt) { while(index == arrWT.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //唤醒瓦特() this.notifyAll(); arrWT[index] = wt; index ++; } //pop用于吃WoTou,当WoTou数为0时wait() public synchronized WoTou pop() { while(index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); index--; return arrWT[index]; } } //继承Runnable接口,实现run方法的Producer类,一个对象只生产20个WoTou class Producer implements Runnable { SyncStack ss = null; Producer(SyncStack ss) { this.ss = ss; } public void run() { for(int i=0; i<20; i++) { WoTou wt = new WoTou(i); ss.push(wt); System.out.println("生产了:" + wt); try { Thread.sleep((int)(Math.random() * 200)); } catch (InterruptedException e) { e.printStackTrace(); } } } } //继承Runnable接口,实现run方法的Consumer类,一个对象只消费20个WoTou class Consumer implements Runnable { SyncStack ss = null; Consumer(SyncStack ss) { this.ss = ss; } public void run() { for(int i=0; i<20; i++) { WoTou wt = ss.pop(); System.out.println("消费了: " + wt); try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
相关文章推荐
- 使用python爬取东方财富网机构调研数据
- Hybrid App - 安全 - 开源实现
- Mactype 解决字体出现剃尾
- sqlserver拆分字符串函数 及应用
- 为RecyclerView打造通用Adapter 让RecyclerView更加好用
- 设计模式读书笔记-----解释器模式
- 构建本地单元测试
- Oracle获取表、表结构的语句
- Quartz2D绘图(3)文字图片
- Nginx做负载均衡无法加载css,js
- 使用Python写Map-Reduce程序
- 从远程服务器向本地系统复制文件(centos之间)
- iOS裁切一个圆形图片-swift
- oracle select ...start with ...connect by ..
- Linux常用命令(一)Linux管理文件和目录的命令
- 什么是web service
- PHP图片采集简陋程序,各位大神拍砖轻点
- Selenium Keys键盘按键包使用实例
- 设计模式读书笔记-----命令模式
- C#学习笔记之自加和自减