JAVA 线程间通信 - 生产者与消费者
2015-01-09 13:33
302 查看
/* 多线程编程 生产者和消费者 */ class Res { private int count=0; private String name; private boolean flag = false; public synchronized void set(String name) { while(flag) try{wait();}catch(Exception e){} this.name = name+ " "+ (++count); System.out.println(Thread.currentThread().getName() + "--生产者--" + this.name); flag = true; this.notifyAll(); } public synchronized void out() { while(!flag) try{this.wait();}catch(Exception e){} System.out.println(Thread.currentThread().getName() + "--消费者----" + this.name); flag = false; this.notifyAll();//唤醒所有的等待线程 } } class Producer implements Runnable { Res r = new Res(); Producer(Res r) { this.r = r; } public void run() { while(true) r.set("商品"); } } class Consumer implements Runnable { Res r = new Res(); Consumer(Res r) { this.r = r; } public void run() { while(true) r.out(); } } class TestDemo { public static void main(String []args) { Res r = new Res(); Producer p = new Producer(r); Consumer c = new Consumer(r); Thread t1 = new Thread(p); Thread t2 = new Thread(c); Thread t3 = new Thread(p); Thread t4 = new Thread(c); t1.start(); t2.start(); t3.start(); t4.start(); } }
相关文章推荐
- java基础12:线程间通信---生产者消费者问题
- 线程通信,生产者消费者问题(Java)
- Java基础——线程间的通信+生产者消费者程序+守护线程+Join方法+线程优先级
- java线程间通信[实现不同线程之间的消息传递(通信),生产者和消费者模型]
- java线程通信 生产者与消费者模式
- 黑马程序员--JAVA基础复习之多线程(三)线程间通信 生产者消费者
- 线程通信,生产者消费者问题(Java)
- Thinking in Java---线程通信+三种方式实现生产者消费者问题
- Java 多线程(三)线程间的通信jdk1.5中Lock,Condition---生产者消费者为例
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- JAVA学习笔记(1)_____模拟线程通信之生产者消费者问题
- java多线程:线程间的通信-生产者和消费者(三)
- JAVA 线程间通信 -生产者消费者JDK5.0升级版
- java多线程线程通信——生产者和消费者
- Java基础复习:线程通信、生产者消费者
- JAVA 线程间通信 - 生产者与消费者
- java多线程-线程间通信_生产者消费者
- Java基础学习__多线程(线程间通信--生产者消费者JDK5.0升级版)
- java线程间通信:生产者--消费者
- Java线程间的相互通信--生产者消费者问题