直接上代碼
注意在使用blockingqueue實現生產者消費者模型時候,BlockingQueue泛型使用若atomic等對象時候會發現消費者出現異常,這是因爲傳值和傳引用的區別,而Integer因爲java的自動裝箱不會出現此類問題,具體可自行嘗試java
生產者ide
public class Pull implements Runnable { BlockingQueue<Integer> pool; Integer product = 0; public Pull(BlockingQueue<Integer> pool) { this.pool = pool; } @Override public void run() { while (true) { try { pool.put(product); System.out.println("add:" + product); product++; } catch (InterruptedException e) { System.out.println("add failed"); e.printStackTrace(); } if (product == 20){ break; } } } }
消費者this
public class Push implements Runnable{ BlockingQueue<Integer> pool; public Push(BlockingQueue<Integer> pool) { this.pool = pool; } @Override public void run() { while(true) { try { Integer tmp = pool.take(); System.out.println("take:" + tmp); } catch (InterruptedException e) { System.out.println("獲取失敗"); e.printStackTrace(); } } } }
主線程atom
public class MyExecutor { public static void main(String[] args) { BlockingQueue<Integer> queue = new LinkedBlockingDeque<>(10); Thread thread = new Thread(new Push(queue)); Thread thread1 = new Thread(new Pull(queue)); thread1.start(); thread.start(); } }