多執行緒之經典生產者消費者問題

2021-06-26 14:19:29 字數 2354 閱讀 9059

通過訊號量,wait,nofity,synchronized來解決生產者消費者問題。

例項如下:

package thread;

public class threadwaitandnotifytest

}class iphone catch (interruptedexception e)

// system.out.println(thread.currentthread().getname()+"第" + (i-1)+ "部iphone已被賣掉。");

} this.name = "iphone 5s("+i+")";

this.issaled = false;

system.out.println(thread.currentthread().getname()+"已生產第"+(i)+"部iphone...");

notify(); // 通知消費者執行緒已生產iphone,等待被賣掉。 }

public synchronized string getname(int i) catch (interruptedexception e)

system.out.println(thread.currentthread().getname()+"wait for sale end...");

} this.issaled = true;

system.out.println(thread.currentthread().getname() + "第"+i+"部iphone已被賣掉。");

notify(); // 通知生產者執行緒該iphone已被賣掉,可以生產下一部了。

return this.name; }}

class producer implements runnable

@override

public void run() catch (interruptedexception e)

} } }

class salesman implements runnable

@override

public void run() catch (interruptedexception e)

} }}

程式執行結果如下:

thread-0正在生產第1部iphone...

thread-0已生產第1部iphone...

thread-1第1部iphone已被賣掉。

thread-0正在生產第2部iphone...

thread-0已生產第2部iphone...

thread-0正在生產第3部iphone...

thread-0第2部iphone等待被賣掉。

thread-1第2部iphone已被賣掉。

thread-0已生產第3部iphone...

thread-0正在生產第4部iphone...

thread-0第3部iphone等待被賣掉。

thread-1第3部iphone已被賣掉。

thread-0已生產第4部iphone...

thread-0正在生產第5部iphone...

thread-0第4部iphone等待被賣掉。

thread-1第4部iphone已被賣掉。

thread-0已生產第5部iphone...

thread-0正在生產第6部iphone...

thread-0第5部iphone等待被賣掉。

thread-1第5部iphone已被賣掉。

thread-0已生產第6部iphone...

thread-0正在生產第7部iphone...

thread-0第6部iphone等待被賣掉。

thread-1第6部iphone已被賣掉。

thread-0已生產第7部iphone...

thread-0正在生產第8部iphone...

thread-0第7部iphone等待被賣掉。

thread-1第7部iphone已被賣掉。

thread-0已生產第8部iphone...

thread-0正在生產第9部iphone...

thread-0第8部iphone等待被賣掉。

thread-1第8部iphone已被賣掉。

thread-0已生產第9部iphone...

thread-0正在生產第10部iphone...

thread-0第9部iphone等待被賣掉。

thread-1第9部iphone已被賣掉。

thread-0已生產第10部iphone...

thread-1第10部iphone已被賣掉。

多執行緒之生產者消費者問題

生產者 producer 消費者consumer 籃子 basket stack 以棧結構代替的籃子,丟進去的饅頭滿足先進後出 問題描述 生產者生產10個饅頭丟進容量只有6的籃子裡面,消費者不斷吃掉籃子中的饅頭。package consumer producer public class consu...

多執行緒之消費者生產者問題

未經過處理的 如下 這裡有兩個問題 首先是對於info物件,生產者可能只新增了webname的資訊,而沒有來得及新增link資訊,程式就切換到了消費者執行緒,消費者執行緒將webname和上乙個info物件的link聯絡到一起。生產者存放了若干次的資料,消費者才開始讀取資料,或者是消費者取完乙個資料...

多執行緒之生產者消費者問題

一 問題概述 是處理併發問題的乙個典型應用。生產者程序和消費者程序同時發生,以此修改快取區buffer的資源。二 模型思路 被管理的資源good,在快取區內 class goods 主程式,再去補充細節 public class testpc 分析下需要,實現思路是快取區類中放有貨物的陣列,生產者程...