线程间通信--等待唤醒机制
2013-09-29 19:36
513 查看
//线程间通信--等待唤醒机制 class Res { String name; String sex; boolean flag = false; } class Input implements Runnable { private Res r; Input(Res r) { this.r = r; } public void run() { int x = 0; while(true) { synchronized(r) { if(r.flag) try{r.wait();}catch(Exception e){} if(x==0) { r.name="mike"; r.sex = "man"; } else { r.name ="丽丽"; r.sex = "女女女"; } x=(x+1)%2; r.flag=true; r.notify(); } } } } class Output implements Runnable { private Res r; Output(Res r) { this.r = r; } public void run() { while(true) { synchronized(r) { if(!r.flag) try{r.wait();}catch(Exception e){} System.out.println(r.name+"...."+r.sex); r.flag = false; r.notify(); } } } } class ThreadDemo { public static void main(String[] args) { Res r= new Res(); Input in = new Input(r); Output out = new Output(r); Thread t1 = new Thread(in); Thread t2 = new Thread(out); t1.start(); t2.start(); } }
相关文章推荐
- 线程通信-等待和唤醒机制和锁(Lock)机制
- 多线程__【线程间通信】【等待唤醒机制】【多生产多消费】【Lock&Condition接口】
- 线程间的通信--等待唤醒机制
- 线程间通信、等待/唤醒机制的使用
- 黑马程序员_JavaSE基础14 之 线程间通信 等待唤醒机制 多生产多消费者 ...
- Java 线程间通信-等待唤醒机制
- 多线程学习笔记(四)之线程间通信---等待唤醒机制
- 利用等待唤醒机制实现线程间的通信
- java线程间通信_线程同步_等待唤醒机制
- (九)Java入门--多线程(4)线程通信--等待唤醒机制
- 线程间通信、等待唤醒机制、生产者消费者问题(Lock,Condition)、停止线程和守护线程、线程优先级
- 24-多线程(线程间通信-等待唤醒机制)1 2图解 3 25-多线程(线程间通信-等待唤醒机制-代码优化)
- 多线程__【线程间通信】【等待唤醒机制】【多生产多消费】【Lock&Condition接口】
- (51)线程间通信,等待唤醒机制
- 线程间的通信------------等待唤醒机制
- java多线程-线程间通信-示例代码-解决安全问题-等待唤醒机制wait()notify()notifyAll()
- day12线程间的通信,等待唤醒机制,生产者消费者问题。新锁lock(): 守护线程,interrupt()停止线程用,join()yield()
- 黑马程序员--线程之间的通信,等待与唤醒机制,线程的终止方式,线程中的其他方法,优先级,toString() 守护线程,GUI图形化界面
- 线程间通信:生产者消费者(等待唤醒机制)
- java多线程——线程间通信之线程等待唤醒机制