生產者消費者模式(synchronized實現)
阿新 • • 發佈:2018-12-30
試著寫了下生產者消費者模式,大致意思是,N個生產者執行緒,M個消費者執行緒。生產者向容器加資料,消費者取資料。當容器size為0,或者滿時。阻塞一類執行緒並交出鎖的擁有權,或者啟用所有執行緒。注意while判斷容器當前容量,因為啟用多個執行緒後操作還要繼續判斷。
public class MyConsumerProductor { ArrayList<String> list=new ArrayList<>(); final private int Capacity = 10; //生產者 class Consumer implements Runnable{ @Override public void run() { while(true) { synchronized(MyConsumerProductor.class) { while(list.size()==Capacity) {//迴圈判斷,因為啟用多個執行緒 try { System.out.println("容量滿了,生產者進入等待"); MyConsumerProductor.class.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(list.size()<10) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } list.add(Thread.currentThread().getName()); System.out.println("product:"+Thread.currentThread().getName()+" size:"+list.size()); if(list.size()==10) { MyConsumerProductor.class.notifyAll(); } } } } } } //生產者 class Productor implements Runnable{ @Override public void run() { while(true) { synchronized(MyConsumerProductor.class) { while(list.size()==0) { try { System.out.println("容量沒了,消費者進入等待"); MyConsumerProductor.class.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(list.size()>0) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("consumer:"+list.remove(list.size()-1)+" size:"+list.size()); if(list.size()==Capacity) { MyConsumerProductor.class.notifyAll(); } } } } } } public static void main(String[] args) { MyConsumerProductor pc=new MyConsumerProductor(); //生產者執行緒 for(int i=0;i<5;i++) { new Thread(pc.new Consumer()).start(); } //消費者執行緒 for(int i=0;i<5;i++) { new Thread(pc.new Productor()).start(); } } }