執行緒的通訊 生產者消費者

2021-07-28 01:56:27 字數 2479 閱讀 6196

public static void main(string agrs)

class resource 

catch (interruptedexception e)

}this.name = name + "--" + cont++;

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

"- producer -"+this.name);

flag = true;

this.notify();

}public synchronized void out()

catch (interruptedexception e)

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

"---- consumer ----"+this.name);

flag = false;

this.notify();}}

class producer implements runnable 

public void run()

}}

class consumer implements runnable 

public void run()

}}

public static void main(string agrs)
會出現生產乙個商品,消費出兩個商品,或者生產兩個而消費乙個

這是因為if語句只判斷一次flag標記,消費者的執行緒生產完會喚醒本方的另一條生產線程,而不判斷flag標記,導致生產兩次而消費一次
然後我們可以把if換成while原因:讓被喚醒的執行緒再一次的判斷

while(flag)

catch (interruptedexception e)

}

但是,新的問題又產生了,執行緒會全部停止原因:執行緒喚醒往往是喚醒執行緒池的第乙個,所以會喚醒本方的執行緒,會導致資料錯亂,加入while後,會導致全部的執行緒都在等待。我們應該喚醒的是消費者的執行緒,所以我們可以用notifyall,喚醒所有的執行緒,因為會while會判斷flag標記,所以不會喚醒生產者的執行緒,而是喚醒消費者的執行緒

notify,容易出現只喚醒本方執行緒的情況,導致程式中的所有執行緒等待

while(flag)

catch (interruptedexception e)

}this.name = name + "--" + cont++;

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

"- producer -"+this.name);

flag = true;

this.notifyall();

public class dealer 

}

class resource 

catch (interruptedexception e)

}this.name = name + "--" + cont++;

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

"- producer -"+this.name);

flag = true;

this.notifyall();

}public synchronized void out()

catch (interruptedexception e)

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

"---- consumer ----"+this.name);

flag = false;

this.notifyall();}}

class producer implements runnable 

public void run()

}}

class consumer implements runnable 

public void run()

}}

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

恢復內容開始 執行緒是作業系統中獨立的個體,但這些個體之間如果沒有特殊的處理就不能成為乙個整體。而執行緒間的通訊機制就是成為整體的必用方案。執行緒間的通訊會使系統的互動性更強,在提高cpu利用率的同時還會使程式設計師對各執行緒任務在處理的過程中進行有效的把控和監督。等待 通知機制 執行緒之間不是獨立...

生產者消費者執行緒

include include include includeusing namespace std typedef int semaphore 訊號量是一種特殊的整型變數 const int size of buffer 5 緩衝區長度 const unsigned short producers...

生產者消費者執行緒

該簡單生產者 消費者執行緒,屬於本人學習過程中的一段練習 如有不足,請指點 package com.lanqiao.demo3 author 大廣子 類說明 簡單的生產者,消費者執行緒 public class threadptcs catch interruptedexception e 退出 s...