生產者-消費者算是併發編程中常見的問題。依靠緩衝區咱們能夠實現生產者與消費者之間的解耦。生產者只管往緩衝區裏面放東西,消費者只管往緩衝區裏面拿東西。這樣咱們避免生產者想要交付數據給消費者,但消費者此時還沒法接受數據這樣的狀況發生。java
這個問題其實就是線程間的通信,因此要注意的是不能同時讀寫。生產者在緩衝區滿的時候不生產,等待;消費者在緩衝區爲空的時候不消費,等待。比較經典的作法是wait
和notify
。編程
生產者線程執行15次set操做安全
public class Producer implements Runnable{ private Channel channel; public Producer(Channel channel) { this.channel = channel; } @Override public void run() { for(int i=0;i<15;i++){ channel.set(Thread.currentThread().getName()+" "+i); } } }
消費者線程執行10次get操做數據結構
public class Consumer implements Runnable { private Channel channel; public Consumer(Channel channel) { this.channel = channel; } @Override public void run() { for(int i=0;i<10;i++){ System.out.println("Consumer "+Thread.currentThread().getName()+" get "+channel.get()); } } }
如今定義Channel類,並建立兩個生產者線程和三個消費者線程併發
public class Channel { private List<String> buffer=new ArrayList<>(); private final int MAX_SIZE=10; public synchronized String get(){ while (buffer.size()==0){//不要用if,醒來了也要再次判斷 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } String str=buffer.remove(0); notifyAll(); return str; } public synchronized void set(String str){ while (buffer.size()==MAX_SIZE){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } buffer.add(str); notifyAll(); } public static void main(String[] args) { Channel channel=new Channel(); Producer producer=new Producer(channel); Consumer consumer=new Consumer(channel); for(int i=0;i<2;i++){ new Thread(producer).start(); } for (int i=0;i<3;i++){ new Thread(consumer).start(); } } }
使用notifyAll而不是notify的緣由是,notify有可能出現屢次喚醒同類的狀況,形成「假死」。咱們可使用Condition來實現更精確的喚醒。ide
將上面代碼中的Channel類修改一下便可this
public class Channel { private List<String> buffer=new ArrayList<>(); private final int MAX_SIZE=10; private Lock lock=new ReentrantLock(); private Condition producer=lock.newCondition(); private Condition consumer=lock.newCondition(); public String get(){ String str=null; try { lock.lock(); while (buffer.size()==0){ consumer.await(); } str=buffer.remove(0); producer.signalAll(); }catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } return str; } public void set(String str){ try { lock.lock(); while (buffer.size()==MAX_SIZE){ producer.await(); } buffer.add(str); consumer.signalAll(); }catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } }
當同步的花銷很是大時,咱們能夠採用雙緩衝區的辦法。雙緩衝的一個好處就在於:由於生產者和消費者各自擁有一個緩衝區,因此他們不會同時對同一個緩衝區進行操做,那麼咱們就不須要爲讀寫操做加鎖,用空間換了時間。在Java中能夠經過Exchanger來交換兩個線程之間的數據結構。線程
public class Producer implements Runnable{ private List<String> buffer; private Exchanger<List<String>> exchanger; public Producer(List<String> buffer, Exchanger<List<String>> exchanger){ this.buffer=buffer; this.exchanger=exchanger; } @Override public void run() { for(int i=0;i<10;i++){ for (int j=0;j<10;j++) buffer.add("Thrad "+Thread.currentThread().getName()+" : "+i+" "+j); try { buffer=exchanger.exchange(buffer); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Consumer implements Runnable { private Exchanger<List<String>> exchanger; private List<String> buffer; public Consumer(List<String> buffer,Exchanger<List<String>> exchanger) { this.exchanger = exchanger; this.buffer = buffer; } @Override public void run() { for(int i=0;i<10;i++){ try { buffer=exchanger.exchange(buffer); } catch (InterruptedException e) { e.printStackTrace(); } for(int j=0;j<10;j++){ String message=buffer.get(0); System.out.println(message); buffer.remove(0); } } } } public class Main { public static void main(String[] args) { List<String> buffer1=new ArrayList<>(); List<String> buffer2=new ArrayList<>(); Exchanger<List<String>> exchanger=new Exchanger<>(); Producer producer=new Producer(buffer1,exchanger); Consumer consumer=new Consumer(buffer2,exchanger); Thread t1=new Thread(producer); Thread t2=new Thread(consumer); t1.start(); t2.start(); } }
咱們可使用更爲方便安全的阻塞式集合來實現生產消費者模型。code
這類集合具備的特色是:當集合已滿或者是爲空的時候,被調用的方法不會當即執行,該方法將被阻塞,直到能夠成功執行爲止。rem
public class Channel { private BlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(10); public String get(){ String str=null; try { str=blockingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } return str; } public void set(String str){ try { blockingQueue.put(str); } catch (InterruptedException e) { e.printStackTrace(); } } }
此次的Channel類是否是比以前的簡潔了許多,有了BlockingQueue咱們就不用再去寫wait和notify了。