多线程上生产者与消费者的有关问题
多线程下生产者与消费者的问题
package com.yql.thread; //生产者与消费者问题java代码实现 public class ProducerConsumer { public static void main(String[] args) { //创建一个栈用来放窝头 SyncStack ss = new SyncStack(); //生产者p Producer p = new Producer(ss); //消费者c Consumer c = new Consumer(ss); //开启生产者消费者线程各两个,模拟两个买窝头两个生产窝头 new Thread(p).start(); new Thread(p).start(); 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; //最多容纳6个窝头 WoTou[] arrWT = new WoTou[6]; //同步出栈的方法 public synchronized void push(WoTou wt) { //只要窝头满栈了就让该线程wait等待其他方法唤醒 while(index == arrWT.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //唤醒其他等待该同步锁的所有线程 this.notifyAll(); arrWT[index] = wt; index ++; } //同步进栈的方法 public synchronized WoTou pop() { //一旦窝头栈空了就让该线程wait等待其他方法唤醒 while(index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //唤醒其他等待该同步锁的所有对象 this.notifyAll(); index--; return arrWT[index]; } } //生产者 实现了runnable接口 可以用于多线程 class Producer implements Runnable { SyncStack ss = null; Producer(SyncStack ss) { this.ss = ss; } //模拟生产20个窝头,每生产一个就将其放入到窝头栈中 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() * 200)); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者 class Consumer implements Runnable { SyncStack ss = null; Consumer(SyncStack ss) { this.ss = ss; } //模拟消费20个窝头 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(); } } } }