溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java 中多線程生產(chǎn)者消費(fèi)者問題詳細(xì)介紹

發(fā)布時(shí)間:2020-09-20 01:11:14 來源:腳本之家 閱讀:115 作者:CC小觀 欄目:編程語言

java 中多線程生產(chǎn)者消費(fèi)者問題

前言:

一般面試喜歡問些線程的問題,較基礎(chǔ)的問題無非就是死鎖,生產(chǎn)者消費(fèi)者問題,線程同步等等,在前面的文章有寫過死鎖,這里就說下多生產(chǎn)多消費(fèi)的問題了

import java.util.concurrent.locks.*;

class BoundedBuffer {
  final Lock lock = new ReentrantLock();//對(duì)象鎖
  final Condition notFull = lock.newCondition(); //生產(chǎn)者監(jiān)視器
  final Condition notEmpty = lock.newCondition(); //消費(fèi)者監(jiān)視器

  //資源對(duì)象
  final Object[] items = new Object[10];
  //putptr生產(chǎn)者角標(biāo),takeptr消費(fèi)者角標(biāo),count計(jì)數(shù)器(容器的實(shí)際長(zhǎng)度)
  int putptr, takeptr, count;

  public void put(Object x) throws InterruptedException {
    //生產(chǎn)者拿到鎖
   lock.lock();
   try {
     //當(dāng)實(shí)際長(zhǎng)度不滿足容器的長(zhǎng)度
    while (count == items.length) 
      //生產(chǎn)者等待
     notFull.await();
    //把生產(chǎn)者產(chǎn)生對(duì)象加入容器
    items[putptr] = x; 
    System.out.println(Thread.currentThread().getName()+"   put-----------"+count);
    Thread.sleep(1000);
    //如果容器的實(shí)際長(zhǎng)==容器的長(zhǎng),生產(chǎn)者角標(biāo)置為0
    if (++putptr == items.length) putptr = 0;
    ++count;
    //喚醒消費(fèi)者
    notEmpty.signal();
   } finally {
     //釋放鎖
    lock.unlock();
   }
  }

  public Object take() throws InterruptedException {
   lock.lock();
   try {
    while (count == 0) 
      //消費(fèi)者等待
     notEmpty.await();
    Object x = items[takeptr]; 
    System.out.println(Thread.currentThread().getName()+"   get-----------"+count);
    Thread.sleep(1000);
    if (++takeptr == items.length) takeptr = 0;
    --count;
    //喚醒生產(chǎn)者
    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();
  }
}



這個(gè)是jdk版本1.5以上的多線程的消費(fèi)者生產(chǎn)者問題,其中優(yōu)化的地方是把synchronized關(guān)鍵字進(jìn)行了步驟拆分,對(duì)對(duì)象的監(jiān)視器進(jìn)行了拆離,synchronized同步,隱式的建立1個(gè)監(jiān)聽,而這種可以建立多種監(jiān)聽,而且喚醒也優(yōu)化了,之前如果是synchronized方式,notifyAll(),在只需要喚醒消費(fèi)者或者只喚醒生產(chǎn)者的時(shí)候,這個(gè)notifyAll()將會(huì)喚醒所有的凍結(jié)的線程,造成資源浪費(fèi),而這里只喚醒對(duì)立方的線程。代碼的解釋說明,全部在源碼中,可以直接拷貝使用。

如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,希望通過本文能幫助到大家,謝謝大家對(duì)本站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI