多線程的等待喚醒機制

一把鎖一把鑰匙。。就是等待跟喚醒要在同一鎖內
/*
多線程的等待喚醒機制
wait();
noyify();

*/
class Pes
{
    String name;
    String sex;
    boolean flag = false;
}
class Inp implements Runnable
{
    private Pes p;
    Inp(Pes p)
    {
        this.p = p;
    }
    public void run()
    {
        int x=0;
        while(true)
        {
            synchronized(p){
                if(p.flag)
                    try{p.wait();}catch(Exception e){}
                if(x==0){
                    p.name ="nike";
                    p.sex = "man";
                }
                else
                {
                    p.name = "mike";
                    p.sex = "women";
                }
                x= (x+1)%2;
                p.flag= true;
                p.notify();
            }
        }
    }
}
class Out implements Runnable
{
    private Pes p;
    Out(Pes p)
    {
        this.p = p;
    }
    public void run()
    {
        while(true)
        {
            synchronized(p)
            {
                if(!p.flag)
                    try{p.wait();}catch(Exception e){}
                System.out.println(p.name+"..."+p.sex);
                p.flag = false;
                p.notify();
            }
        }
    }
}
class Test_12_3
{
    public static void main(String[] args)
    {
        System.out.println("Hello Wolrd");
        Pes p = new Pes();
        Inp i = new Inp(p);
        Out o = new Out(p);
        Thread t1 = new Thread(i);
        Thread t2 = new Thread(o);
        t1.start();
        t2.start();
    }
}
//notifyAll();
/*
wait:
notify();
notifyAll();
都使用在同步中。由於要對持有監視器(鎖)的線程操做。
因此要使用在同步中,由於只有同步才具備鎖。
爲何這些操做線程的方法要定義Object類中呢?
由於這些方法在操做同步中線程時,都必需要標識它們所操做線程只有的鎖。
只有用一個鎖上的被等待線程。能夠被同一個鎖上notify喚醒。
不能夠對不一樣鎖中的線程進行喚醒。
也就是說。等待和喚醒必須是同一個鎖
*/
相關文章
相關標籤/搜索