1. 程式人生 > >多執行緒生產者消費者問題

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

一般面試喜歡問些執行緒的問題,較基礎的問題無非就是死鎖,生產者消費者問題,執行緒同步等等,在前面的文章有寫過死鎖,這裡就說下多生產多消費的問題了

import java.util.concurrent.locks.*;

class BoundedBuffer {
   final Lock lock = new ReentrantLock();//物件鎖
   final Condition notFull  = lock.newCondition(); //生產者監視器
   final Condition notEmpty = lock.newCondition(); //消費者監視器

   //資源物件
final Object[] items = new Object[10]; //putptr生產者角標,takeptr消費者角標,count計數器(容器的實際長度) int putptr, takeptr, count; public void put(Object x) throws InterruptedException { //生產者拿到鎖 lock.lock(); try { //當實際長度不滿足容器的長度 while (count == items.length) //生產者等待 notFull.await(); //把生產者產生物件加入容器
items[putptr] = x; System.out.println(Thread.currentThread().getName()+" put-----------"+count); Thread.sleep(1000); //如果容器的實際長==容器的長,生產者角標置為0 if (++putptr == items.length) putptr = 0; ++count; //喚醒消費者 notEmpty.signal(); } finally { //釋放鎖
lock.unlock(); } } public Object take() throws InterruptedException { lock.lock(); try { while (count == 0) //消費者等待 notEmpty.await(); Object x = items[takeptr]; System.out.println(Thread.currentThread().getName()+" get-----------"+count); Thread.sleep(1000); if (++takeptr == items.length) takeptr = 0; --count; //喚醒生產者 notFull.signal(); return x; } finally { //釋放鎖 lock.unlock(); } } } class Consu implements Runnable{ BoundedBuffer bbuf; public Consu(BoundedBuffer bbuf) { super(); this.bbuf = bbuf; } @Override public void run() { while(true){ try { bbuf.take() ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Produ implements Runnable{ BoundedBuffer bbuf; int i=0; public Produ(BoundedBuffer bbuf) { super(); this.bbuf = bbuf; } @Override public void run() { while(true){ try { bbuf.put(new String(""+i++)) ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //主方法 class Lock1{ public static void main(String[] args) { BoundedBuffer bbuf=new BoundedBuffer(); Consu c=new Consu(bbuf); Produ p=new Produ(bbuf); Thread t1=new Thread(p); Thread t2=new Thread(c); t1.start(); t2.start(); Thread t3=new Thread(p); Thread t4=new Thread(c); t3.start(); t4.start(); } }

這個是jdk版本1.5以上的多執行緒的消費者生產者問題,其中優化的地方是把synchronized關鍵字進行了步驟拆分,對物件的監視器進行了拆離,synchronized同步,隱式的建立1個監聽,而這種可以建立多種監聽,而且喚醒也優化了,之前如果是synchronized方式,notifyAll(),在只需要喚醒消費者或者只喚醒生產者的時候,這個notifyAll()將會喚醒所有的凍結的執行緒,造成資源浪費,而這裡只喚醒對立方的執行緒。程式碼的解釋說明,全部在原始碼中,可以直接拷貝使用。