146 多執行緒 執行緒間通訊 生產者消費者

2021-09-02 12:42:19 字數 1669 閱讀 8258

乙個生產者乙個消費者

class producerconsumer

}class resourcecatch(exception e){}

this.name = name +"--"+count++;

system.out.println(thread.currentthread().getname()+

"-生產者-"+this.name);

flag = true;

this.notify();

}public synchronized void out()catch(exception e){}

system.out.println(thread.currentthread().getname()+

"-消費者-"+this.name);

flag = false;

this.notify();}}

class producer implements runnable

public void run()}}

class consumer implements runnable

public void run()

}}

兩個生產者兩個消費者。改動如下。

class producerconsumer

}

執行結果會出現另外兩種情況:

1.生產者生成了兩次,消費者只取一次

2.生產者生成一次,消費者取兩次

發生這兩種情況是因為沒有判斷標記flag。需要將if(flag)改為while(flag)。

但只修改這點,會導致所有程序都處於全部等待狀態。所以要把notify()改為notifyall();

/*對於多個生產者和消費者

為什麼要定義while判斷標記?

原因:讓被喚醒的執行緒再進行一次標記判斷

為什麼定義notifyall()?

因為需要喚醒對方執行緒。用notify()容易出現喚醒

本方執行緒的情況,導致程式中的所有執行緒都等待。

*/class producerconsumer

}class resourcecatch(exception e){}

this.name = name +"--"+count++;

system.out.println(thread.currentthread().getname()+

"-生產者-"+this.name);

flag = true;

this.notifyall();

}public synchronized void out()catch(exception e){}

system.out.println(thread.currentthread().getname()+

"-消費者-"+this.name);

flag = false;

this.notifyall();}}

class producer implements runnable

public void run()}}

class consumer implements runnable

public void run()

}}

執行緒間通訊 生產者與消費者(多執行緒)

從單執行緒變成多執行緒,想著本來程式裡的判斷語句是 if,而if只判斷一次,想著換成while flag 結果會出現生產乙個商品,消費兩個,或者生產兩個消費乙個的情況,後來才發現把程式中的 notify 全部變成notifyall 就解決了這個問題。public class producercons...

NSCondition 多執行緒解決生產者消費者問題

import viewcontroller.h inte ce viewcontroller 資料緩衝區 property strong,nonatomic nsmutablearray products 執行緒鎖 property strong,nonatomic nscondition cond...

執行緒 執行緒間通訊(生產者消費者模式)

注意 1.執行緒間的通訊,共享的資料一定要有同步 塊synchronized 2.一定要有wait和notify,而且二者一定是成對出現 3.生產者和消費者的執行緒實現一定是在while true 裡面public class basket public void setempty boolean ...