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();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean hasValue = false;
public synchronized void setRes(String name,String sex){
if(hasValue){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name;
this.sex = sex;
hasValue = true;
this.notify();
}
public synchronized void printf(){
if(hasValue){
System.out.println(name+"..."+sex);
hasValue = false;
this.notify();
}
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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){
if(x==0){
r.setRes("john", "man");
}else{
r.setRes("小花", "女");
}
x = (x+1)%2;
}
}
}
class Output implements Runnable{
private Res r ;
Output(Res res){
this.r = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
r.printf();
}
}
}