java 线程之间的通讯

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;
            }
        }
    }
}
posted @ 2012-09-07 15:34  ligang305  阅读(115)  评论(0编辑  收藏  举报