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

2021-07-07 05:11:31 字數 893 閱讀 2642

/*

從單執行緒變成多執行緒,想著本來程式裡的判斷語句是 if,而if只判斷一次,

想著換成while(flag),結果會出現生產乙個商品,消費兩個,或者生產兩個消費乙個的情況,

後來才發現把程式中的 notify()全部變成notifyall()就解決了這個問題。

*/public class producerconsumerdemo2

}class resouce2

catch(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 producer2 implements runnable

public void run()

}class consumer2 implements runnable

public void run()

}

結果:

有點亂啊。。。。。。。。。。。。。。。。。。。。

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

乙個生產者乙個消費者 class producerconsumer class resourcecatch exception e this.name name count system.out.println thread.currentthread getname 生產者 this.name f...

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

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

多執行緒 生產者消費者

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