多執行緒 模擬生產者消費者問題

2022-06-06 14:15:10 字數 2271 閱讀 4374

分別用管程法和訊號燈法模擬生產者消費者問題

應用場景:生產者和消費者問題

◆假設倉庫中只能存放一件產品,生產者將生產出來的產品放入倉庫,消費者將倉庫中產品取走消費.◆如果倉庫中沒有產品,則生產者將產品放入倉庫,否則停止生產並等待,直到倉庫中的產品被消費者取走為止.

◆如果倉庫中放有產品,則消費者可以將產品取走消費,否則停止消費並等待,直到倉庫中再次放入產品為止.

這是乙個執行緒同步問題,生產者和消費者共享同乙個資源,並且生產者和消費者之間相互依賴,互為條件.

◆對於生產者,沒有生產產品之前,要通知消費者等待.而生產了產品之後,又

需要馬.上通知消費者消費

◆對於消費者, 在消費之後,要通知生產者已經結束消費,需要生產新的產品以供消費.

◆在生產者消費者問題中,僅有synchronized是不夠的

◆synchronized 可阻止併發更新同乙個共享資源,實現了同步

◆synchronized 不能用來實現不同執行緒之間的訊息傳遞(通訊)

1.測試:生產者消費者模型-->利用緩衝區解決:管程法

package

com.cl.pu;

//測試:生產者消費者模型-->利用緩衝區解決:管程法

//生產者:消費者,產品,緩衝區

public

class

testpc }//

生產者class producer extends

thread

//生產

@override

public

void

run()

}}//

消費者class consumer extends

thread

//消費

@override

public

void

run()

}}//

產品class

chicken}//

緩衝區class

syncontainer

//如果沒有滿,就放入產品

chickens[count]=chicken;

count++;

//通知消費者消費

}

//消費者消費產品

public

synchronized

chicken pop()

//如果可以消費

count--;

chicken chicken=chickens[count];

//產品沒了,通知生產者生產

return

chicken;

}}

package

com.cl.pu;

//訊號燈法,2個執行緒模擬生產者消費者

public

class

testpc2 }//

生產者class player extends

thread

@override

public

void

run()

else

}}}//

消費者class watcher extends

thread

@override

public

void

run()

}}//

產品,節目

class

tv catch

(interruptedexception e)

}system.out.println("演員表演了:"+voice);

//通知觀眾**

this.notifyall();//

通知喚醒

this.voice=voice;

this.flag=!this

.flag;

}//**

public

synchronized

void

watch()

catch

(interruptedexception e)

}system.out.println("**了:"+voice);

//通知演員表演

this

.notifyall();

this.flag=!this

.flag;

}}

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

從上乙個小測試當中,我們會發現執行緒之間存在爭奪問題,所以在這裡用上了訊號鎖 include include include include include include include define max size 5 struct data structpro max size sem t ...

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

package multithreading.pc 測試 生產者消費者模型 利用緩衝區解決 管程法 生產者,消費者,產品,緩衝區 public class testpc 生產者 class productor extends thread 生產 override public void run 消費...

多執行緒 生產者消費者

這個就不多說了,直接上 include include using namespace std const unsigned short size of buffer 10 緩衝區長度 unsigned short productid 0 產品號 unsigned short consumeid 0...