多线程:生产者与消费者经典问题(马士兵)
来源:互联网 发布:中铁宝桥网络大学 编辑:程序博客网 时间:2024/06/12 18:55
package houy.qing.demo;public class ProducerSummer { public static void main(String[] args) { SyncStack ss = new SyncStack(); new Thread(new Producer(ss)).start(); new Thread(new Consumer(ss)).start(); }}class WoTo{ int id; public WoTo(int id){ this.id = id; } public String toString() { return "woto :" + id; }}class SyncStack{ int index = 0; WoTo[] arrWoTo = new WoTo[6]; public synchronized void push(WoTo wt){ while (index == arrWoTo.length) { try { System.out.println("系统当前时间:" + System.currentTimeMillis()); this.wait(5*1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("系统当前时间:" + System.currentTimeMillis()); this.notify(); arrWoTo[index] = wt; System.out.println("生产:"+ wt); index++; } public synchronized WoTo pop(){ while (index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; return arrWoTo[index]; } }class Producer implements Runnable{ SyncStack ss = null; public Producer(SyncStack ss) { this.ss = ss; } @Override public void run() { for (int i = 0; i < 20; i++) { WoTo wt = new WoTo(i); ss.push(wt); try { Thread.sleep((int)Math.random()*200); } catch (InterruptedException e) { e.printStackTrace(); } } }}class Consumer implements Runnable{ SyncStack ss = null; public Consumer(SyncStack ss) { this.ss = ss; } @Override public void run() { for (int i = 0; i < 20; i++) { WoTo wtTo = ss.pop(); System.out.println("消费:" + wtTo); try { Thread.sleep((int)Math.random()*1000); } catch (InterruptedException e) { e.printStackTrace(); } } }}
阅读全文
0 0
- 多线程:生产者与消费者经典问题(马士兵)
- 马士兵视频中的生产者与消费者的经典问题
- 多线程经典问题-生产者与消费者
- Java经典多线程问题--生产者与消费者
- 马士兵-多线程学习第05课 生产者消费者问题
- java多线程实现生产者与消费者---经典问题
- 多线程-生产者与消费者问题
- 马士兵生产者消费者
- 多线程经典——生产者消费者问题(加锁版)
- 多线程八 生产者消费者经典问题
- java多线程之生产者消费者经典问题
- 经典多线程实例:生产者消费者问题
- 多线程之经典生产者消费者问题
- java多线程之生产者消费者经典问题
- 多线程第八篇 生产者消费者经典问题
- 多线程八 生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- 写一个 function,它遍历一个对象数组(第一个参数)并返回一个包含相匹配的属性-值对(第二个参数)的所有对象的数组。
- 12-spring的事务管理(转账环境搭建一)
- 村民排队(uva 11174)
- Qt实用技巧:qtwidget中pushbutton成为可点击的图标(实现全透明,不论点击与否都只显示Icon)
- 求大神指导,这个AlexNet Tersorflow哪里有问题?
- 多线程:生产者与消费者经典问题(马士兵)
- 面向对象-子父类中变量的特点
- IntelliJ IDEA(2017)安装和破解
- Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
- 代码收录-MFC 窗口透明
- 首字母转大写
- 关闭linux防火墙永久
- 病毒分析练习
- cmd中输入net start mysql提升:服务器无效怎么版