package thread; /** * *功能: 厨师生产馒头放入框中,售货员从框中取出馒头卖出,模拟生产者与消费者线程 */ public class ProducerConsumer { public static void main(String[] args) { // TODO Auto-generated method stub SyncStack ss = new SyncStack(); //定义一个框 Producer p = new Producer(ss); //定义一个生产者 Consumer c = new Consumer(ss); //定义一个消费者 new Thread(p).start(); //消费者线程 new Thread(c).start(); //生产者线程 } } //馒头个体 class WoTou{ //定义一个窝头对象 int id; WoTou(int id){ this.id = id; //存储馒头号 } public String toString(){ return "WoTou: "+ id; } } //框的生成 class SyncStack{ int index = 0; WoTou[] arrWT = new WoTou[6]; public synchronized void push(WoTou wt){ if(index == arrWT.length){ //比较危险 如果出现异常,将会跳过等待,等待不能够顺利完成,一般都是用while try { this.wait(); //让当前正在访问该对象的线程等待 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify(); //叫醒一个正在等待在该对象上的线程 arrWT[index] = wt; index++; } public synchronized WoTou pop(){ if(index == 0){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify(); // 英文意思通知 叫醒一个正在等待在该对象上的线程 index--; return arrWT[index]; } } //生产者 class Producer implements Runnable{ SyncStack ss = null; Producer(SyncStack ss){ this.ss = ss; } @Override public void run() { for(int i = 0; i<20; i++){ WoTou wt = new WoTou(i); //生产一个馒头 ss.push(wt); //将馒头放入框中 System.out.println("生产了:"+wt); try { Thread.sleep((int)Math.random()*1000); //线程睡眠 } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者 class Consumer implements Runnable{ SyncStack ss = null; Consumer(SyncStack ss){ this.ss = ss; } @Override public void run() { for(int i = 0; i<20; i++){ WoTou wt = ss.pop(); //将馒头卖出去 System.out.println("消费了:"+wt); try { Thread.sleep((int) (Math.random()*1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
多线程 生产者与消费者
猜你喜欢
转载自blog.csdn.net/qq_32270067/article/details/78116050
今日推荐
周排行