java 线程之间的通讯
2012-09-07 15:34
471 查看
package com.chnsys.threaddemo; public class JavaResearch { /** * @param args * 模拟死锁 * */ //等待唤醒机制 /*1:input: flag flag == flase: 设值-->置为true-->notify-->wait flag == true: wait 2:output: flag == true: 输出-->置为false-->notify-->wait flag == flase: notify-->wait */ public static void main(String[] args) { // TODO Auto-generated method stub 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(); } } class Res{ String name; String sex; boolean hasValue = false; } class Input implements Runnable{ private Res r ; Input(Res res){ this.r = res; } @Override public void run() { int x = 0; // TODO Auto-generated method stub while(true){ synchronized (Input.class) { if(r.hasValue){ try { Input.class.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } if(x==0){ r.name = "john"; r.sex = "boy"; }else{ r.name = "小花"; r.sex = "女"; } x = (x+1)%2; Input.class.notifyAll(); r.hasValue = true; } } } } class Output implements Runnable{ private Res r ; Output(Res res){ this.r = res; } @Override public void run() { // TODO Auto-generated method stub while(true){ synchronized (Input.class) { if(!r.hasValue){ try { Input.class.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+ " "+r.name+ " "+r.sex); Input.class.notifyAll(); r.hasValue = false; } } } }
相关文章推荐
- 线程之间通讯--java.lang.IllegalMonitorStateException
- Guava关于JAVA中系统组件之间交互通讯(非线程之间通讯)
- java线程基础巩固---多Produce多Consume之间的通讯导致出现程序假死的原因分析
- java 中多线程之间的通讯之生产者和消费者 (多个线程之间的通讯)
- java线程之间通讯
- Guava关于JAVA中系统组件之间交互通讯(非线程之间通讯)
- 线程开发之多线程之间的通讯实现
- 线程之间的通讯---SynchronizationContext [转]
- 使用JAVA线程写的一个UDP简易通讯程序(三)
- Java 编程下的并发线程之间的同步代码块死锁
- ICE学习之C# Java之间通讯
- Java高并发编程:多个线程之间共享数据的方式探讨
- java与C++之间进行SOCKET通讯要点简要解析
- 线程之间的通讯- UI 通讯使用SynchronizationContext--(1)
- JAVA 进程与线程之间的区别与联系
- Java 多线程编程之六:线程之间的通信(附源代码)
- Java实现多个线程之间的管理 --- CountDownLatch
- java并发-多线程之多个线程之间共享数据(6)
- (转载)Java里快如闪电的线程间通讯