Java学习(7):同步问题之生产者与消费者的问题
生产者生产馒头,消费者消费馒头。一个篮子,生产者往篮子中放馒头,消费者从篮子中取馒头。
/** * 这是一个篮子类 * * @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]; // 用来标记篮子中馒头的数量 private int 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 *@time 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 *@time 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 *@time 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(); } }