文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>JAVA,生产者消费者代码示例

JAVA,生产者消费者代码示例

时间:2010-10-14  来源:robbiezr

代码来源于网络,根据自己的理解进行了少量修改。  
package producerAndConsumer;

public class ProducerConsumer {
  public static void main(String[] args) {
    SyncStack ss = new SyncStack();
    Producer p = new Producer(ss, "Eddie");
    Consumer c = new Consumer(ss);
    
    new Thread(c).start();
    new Thread(p).start();
  }
}

//生产品
class Bread {
  int id;

  Bread(int id) {
    this.id = id;
  }

  public String toString() {
    return "Bread : " + id;
  }
}

//同步缓冲区
class SyncStack {
  int index = 0;
  Bread[] arrBread = new Bread[20];

  //入栈
  public synchronized void push(Bread wt) {
    //缓冲区满后,则调用线程等待
    while (index == arrBread.length) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    arrBread[index] = wt;
    index++;
    /**
     * 通知所有消费者
     * 若不加入notify调用,处于wait状态的消费者将一直等待下去。
     */
    this.notifyAll();
  }

  //出栈
  public synchronized Bread pop() {
    //缓冲区为空时,则调用线程等待
    while (index == 0) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    index--;
    /**
     * 通知所有生产者
     * 若不加入notify调用,处于wait状态的生产者将一直等待下去。
     */
    this.notifyAll();
    return arrBread[index];
  }
}

class Producer implements Runnable {
  SyncStack ss = null;
  String name;

  Producer(SyncStack ss, String n) {
    this.ss = ss;
    this.name = n;
  }

  public void run() {
    for (int i = 0; i < 20; i++) {
      Bread bd = new Bread(i);
      ss.push(bd);
      System.out.println(this.name + "生产了:" + bd);
      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;
  }

  public void run() {
    for (int i = 0; i < 20; i++) {
      Bread bd = ss.pop();
      System.out.println("消费了: " + bd);
      try {
        Thread.sleep((int) (Math.random() * 1000));
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
排行榜 更多 +
泡龙大闯关安卓版

泡龙大闯关安卓版

冒险解谜 下载
割草派对安卓版

割草派对安卓版

飞行射击 下载
堡垒攻防战安卓版

堡垒攻防战安卓版

飞行射击 下载