線程運用---等待通知的範式wait()、notify()

1.等待線程獲取到對象的鎖,調用wait()方法,放棄鎖,進入等待隊列

2.通知線程獲取到對象的鎖,調用對象的notify()方法

3.等待線程接受到通知,從等待隊列移到同步隊列,進入阻塞狀態

4.通知線程釋放鎖後,等待線程獲取到鎖繼續執行


以下爲代碼示例:

接收等待的實體

public class Express {

public final static StringCITY ="BeiJing";

private int km;/*運輸里程數*/

private Stringsite;/*到達地點*/

public Express() {

}

public Express(int km, String site) {

this.km = km;

this.site = site;

}

/* 變化公里數,然後通知處於wait狀態並需要處理公里數的線程進行業務處理*/

public synchronized void changeKm(){

this.km =101;

notify();

}

/* 變化地點,然後通知處於wait狀態並需要處理地點的線程進行業務處理*/

public  synchronized  void changeSite(){

this.site ="BeiJing";

notifyAll();

}

/*線程等待公里的變化*/

public synchronized void waitKm(){

while(this.km<100){

try {

wait();

System.out.println("Check Site thread[" +Thread.currentThread().getId()+"] is be notified");

}catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("the Km is "+this.km+",I will change db");

}

/*線程等待目的地的變化*/

public synchronized void waitSite(){

while(this.site.equals(CITY)){//快遞到達目的地

try {

wait();

System.out.println("Check Site thread["+Thread.currentThread().getId()+"] is be notified");

}catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("the site is "+this.site+",I will call user");

}

}

開啓線程修改數據的變化

public class TestWN {

private static Expressexpress =new Express(0,Express.CITY);

/*檢查里程數變化的線程,不滿足條件,線程一直等待*/

private static class CheckKmextends Thread{

@Override

public void run() {

express.waitKm();

}

}

/*檢查地點變化的線程,不滿足條件,線程一直等待*/

private static class CheckSiteextends Thread{

@Override

public void run() {

express.waitSite();

}

}

public static void main(String[] args)throws InterruptedException {

for(int i=0;i<3;i++){

new CheckSite().start();

}

for(int i=0;i<3;i++){

new CheckKm().start();

}

Thread.sleep(1000);

express.changeKm();//快遞地點變化

}

}

 

 

以上內容僅代表個人學習的見解,希望可以爲大家提供一個學習參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章