生产者--消费者实践
2015-12-15 00:00
211 查看
/** * 一个场景,共同的资源 * 生产者消费者模式 信号灯法 * wait():等待,释放锁 sleep():不释放锁 * notify():释放锁 * @author Administrator * */ public class Movie { private String pic; //信号灯 //flag -->T 生产者生产,消费者等待,生产完成后通知消费 //flag -->F 消费者消费,生产者等待,消费完成后通知生产 private boolean flag = true; /** * 播放 * @param pic */ public synchronized void play(String pic){ if(!flag){//生产者等待 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //开始生产 try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("生产了"+pic); //生产完毕 this.pic = pic; //通知消费 this.notify(); //生产者停下 this.flag=false; } public synchronized void watch(){ if(flag){//消费者等待 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //开始消费 try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("消费了"+pic); //消费完毕 //通知生产 this.notifyAll(); //消费停止 this.flag = true; } } /** * 生产者 * @author Administrator * */ public class Player implements Runnable{ private Movie m; public Player(Movie m) { super(); this.m = m; } @Override public void run() { for(int i=0;i<20;i++){ if(i%2==0){ m.play("左青龙"); }else{ m.play("右白虎"); } } } } /** * 消费者 * @author Administrator * */ public class Watcher implements Runnable { private Movie m; public Watcher(Movie m) { super(); this.m = m; } @Override public void run() { for(int i=0;i<20;i++){ m.watch(); } } } public class App { public static void main(String[] args) { //共同的资源 Movie m = new Movie(); //线程 Player p = new Player(m); Watcher w = new Watcher(m); new Thread(p).start(); new Thread(w).start(); } }
相关文章推荐
- HTML-标签的语义化
- nginx 启动脚本
- memcache 启动脚本
- sysbetch 安装
- sysbench OLTP基准测试
- [转]关于mysql中explain的那些事儿
- python读取超大文件
- Jenkins startup
- maven依赖关系中Scope的作用
- 关于Zookeeper使用实例
- MindMapper中的鱼骨图该怎样进行设置
- FineReport中Domino数据库连接方法
- 导出excel功能解剖
- Linux环境下修改mysql用户密码(忘记密码)
- System Verilog Assertion for debug
- 教你ZBrush®功能特性之法线贴图
- 窗设备(http://www.shtianlijiqi.com/sgmcsb/)
- C# EXcel 打印
- 数据库更新字段部分内容的语句
- 【插入排序】直接插入排序