執行緒同步wait notify小例子

2021-06-28 02:06:22 字數 1008 閱讀 1977

執行緒同步小例子:開啟兩個執行緒實現拿雞蛋 放雞蛋交叉進行
public class dofunction  catch (interruptedexception e) 

} num--;

system.out.println("拿雞蛋");

notify(); }

public synchronized void setegg() catch (interruptedexception e)

} num++;

system.out.println("放雞蛋");

notify();

}}

public class testtread 

}/**

* 對於同一物件而言才存在同步的問題,所以有乙個接受物件的構造方法

* */

class seteggthread implements runnable

@override

public void run() }}

class getegethread extends thread

@override

public void run()

}}

放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋放雞蛋

拿雞蛋

執行緒間通訊 wait notify

執行緒間通過鎖物件進行同步,將鎖加在多個執行緒共同訪問的資源上,實現多個執行緒的同步 執行緒間 可以通過 notify notifyall wait 方法進行排程,wait 必須用在同步 塊或同步方法裡,鎖物件呼叫wait 後,釋放同步方法鎖,給其他具有同等優先順序,或者更高優先順序的執行緒執行,p...

執行緒間的通訊 wait notify

package com.jjyy.thread 執行緒間的通訊 假設有兩個執行緒,a和b。共同擁有乙個同步物件,lock。1 首先,執行緒a通過synchronized lock 獲得lock同步物件,然後呼叫lock.wait 函式,放棄lock同步物件,執行緒a停止執行,進入等待佇列。2 執行緒...

Java多執行緒wait,notify例項

package com.lj.thread2 public class sample catch interruptedexception e number system.out.println number increased by thread.currentthread getname num...