Java學習(7):同步問題之生產者與消費者的問題
阿新 • • 發佈:2017-07-22
con runnable pop pre 標記 this auth style about
生產者生產饅頭,消費者消費饅頭。一個籃子,生產者往籃子中放饅頭,消費者從籃子中取饅頭。
/** * 這是一個籃子類 * * @author xcx * @time 2017年7月21日上午10:01:32 */ public class Basket { // 籃子裏最多可以裝10個饅頭 private final int Max_Numbers_StreamedBread = 10; SteamedBread[] sbBreads = new SteamedBread[Max_Numbers_StreamedBread]; // 用來標記籃子中饅頭的數量 privateint index = 0; // 向籃子中放饅頭的方法 public synchronized void push(SteamedBread sbBread) { while (index >= Max_Numbers_StreamedBread) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }this.notify(); sbBreads[index] = sbBread; index++; } // 從籃子中拿饅頭的方法 public synchronized SteamedBread pop() { while (index <= 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }return null; } this.notify(); index--; return sbBreads[index]; } }
/** *消費者類 *@author xcx [email protected] 2017年7月21日上午10:23:53 */ public class Consumer implements Runnable { Basket b = new Basket(); private SteamedBread steamedBread; public Consumer(Basket b){ this.b = b; } @Override public void run() { for(int i=0;i<20;i++){ steamedBread = b.pop(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(steamedBread == null){ }else{ System.out.println("消費"+steamedBread); } } } }
/** * 這是一個生產者類 * * @author xcx * @time 2017年7月21日上午10:16:25 */ public class Producer implements Runnable { private Basket b = new Basket(); public Producer(Basket b){ this.b = b; } @Override public void run() { for(int i=0;i<20;i++){ SteamedBread sBread = new SteamedBread(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("生產了第"+i+"個饅頭"); b.push(sBread); } } }
/** *this is a class about SteamedBread *@author xcx [email protected] 2017年7月21日上午9:59:16 */ public class SteamedBread { private int i; public SteamedBread(int i){ this.i = i; } @Override public String toString() { return "第"+i+"個饅頭"; } }
/** *同步線程測試類 *@author xcx [email protected] 2017年7月21日上午10:44:10 */ public class Test { public static void main(String[] args) { //創建籃子的對象 Basket basket = new Basket(); //創建生產者線程和消費者線程 Producer producer = new Producer(basket); Consumer consumer = new Consumer(basket); Thread t1 = new Thread(producer); Thread t2 = new Thread(consumer); t1.start(); t2.start(); } }
Java學習(7):同步問題之生產者與消費者的問題