生产者消费者模型--2个线程
2015-10-18 18:55
417 查看
package comm; public class ProducerConsumerDemo { public static void main(String[] args) { Resource r = new Resource(); Producer pro = new Producer(r); Consumer con = new Consumer(r); Thread t1 = new Thread(pro); Thread t2 = new Thread(con); t1.start(); t2.start(); } } class Resource { private String name; private int count = 1; private boolean flag = false; public synchronized void set(String name) { if (flag) try { this.wait(); } catch (InterruptedException e) { } this.name = name + "==" + (count++); System.out.println(Thread.currentThread().getName() + "==producer==" + this.name); flag = true; this.notify(); } public synchronized void out() { if (!flag) try { this.wait(); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + "====consumer====" + this.name); flag = false; this.notify(); } } class Producer implements Runnable { private Resource res; Producer(Resource res) { this.res = res; } public void run() { while (true) res.set("+商品+"); } } class Consumer implements Runnable { private Resource res; Consumer(Resource res) { this.res = res; } public void run() { while (true) res.out(); } }
相关文章推荐
- HDU 1358 Period (KMP)
- SEO为什么越来越难?
- 生产者消费者--多个线程出现的问题
- 信息安全系统设计第五周实验报告
- 生产者消费者--多个线程出现的问题
- QString的使用
- 软件测试管理--第二章 2.2节
- 【安卓面试笔记】(二)Activity 的四种加载模式
- 黑马程序员——OC学习笔记07 Block 和 protocol协议。
- ios 生成随机数
- alphn和beta测试的区别
- 商务部等六部委令2006年第10号公布《关于外国投资者并购境内企业的规定》
- HTML 注册事件向引用方法中的传参问题的两个方式
- Tomcat下为每个Web应用配置不同的访问端口
- 不要让四舍五入亏了一方
- 软件测试管理--第一章 1.2节
- Nginx
- Java IO5:字符流
- css标签
- hadoop开发环境-----eclipse