您的位置:首页 > 编程语言 > Java开发

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;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: