執行緒間通訊

2021-08-14 20:51:48 字數 1406 閱讀 9280

/*

執行緒間通訊:

其實就是多個執行緒在操作同乙個資源,

但是操作的動作不同。

*/class res

class input implements runnable

public void run()

catch(exception e){}       //等待

if(x==0)

else

x = (x+1)%2;

r.flag = true;

r.notify();   //喚醒}}

}}class output implements runnable

public void run()

catch(exception e){}

system.out.println(r.name+"...."+r.***);

r.flag = false;

r.notify();            //喚醒}}

}}class  inputoutputdemo

}//notifyall();

/*wait:

notify();

notifyall();

都使用在同步中,因為要對持有監視器(鎖)的執行緒操作。

所以要使用在同步中,因為只有同步才具有鎖。

為什麼這些操作執行緒的方法要定義object類中呢?

因為這些方法在操作同步中線程時,都必須要標識它們所操作執行緒只有的鎖,

只有同乙個鎖上的被等待執行緒,可以被同乙個鎖上notify喚醒。

不可以對不同鎖中的執行緒進行喚醒。

也就是說,等待和喚醒必須是同乙個鎖。

而鎖可以是任意物件,所以可以被任意物件呼叫的方法定義object類中。

**優化

class res         

catch(exception e){}

this.name = name;

this.*** = ***;                   //將區域性變數的值傳遞給成員變數

flag = true;

this.notify();

}public synchronized void out()

catch(exception e){}

system.out.println(name+"........"+***);

flag = false;

this.notify();}}

class input implements runnable

public void run()}}

class output implements runnable

public void run()}}

class  inputoutputdemo2

}

執行緒間通訊

執行緒間通訊 多個執行緒在操作統一資源,但各個執行緒操作的動作不同。資源 class res class input implements runnable public void run else x x 1 2 class output implements runnable public vo...

執行緒間通訊

執行緒間的通訊 在乙個多執行緒的應用程式中,所有執行緒共享程序資源,協同工作。所以,執行緒之間的通訊是編寫多執行緒 應用的必不可少的環節。執行緒之間的通訊包括互斥 同步等,它是多 執行緒設計中最難控制的部分,也是關鍵部分。執行緒間的互斥 1 臨界區 在乙個多執行緒 的應用程式中,可能存在這樣的危險 ...

執行緒間通訊

執行緒間通訊 其實就是多個執行緒在操作同乙個資源 但是操作的動作不同。等待喚醒機制 wait notify 0 notifyall 都使用在同步中,因為要對持有監視器 鎖 的執行緒操作。所以要使用在同步中,因為只有同步才具有鎖 為什麼這些操作執行緒的方法要定義object類中呢?因為這些方法在操作同...