我思故我强

多线程-生产者消费者

 

package test;

class Thing {
 int id;

 public Thing(int id) {
  this.id = id;
 }
}

class Stack {
 int counter = 0;
 int stackSize;
 Thing[] things = null;

 public Stack(int stackSize) {
  this.stackSize = stackSize;
  things = new Thing[stackSize];
 }

 public synchronized void push(Thing thing) {
  // 生产
  while (counter == stackSize) {
   // 已经满了 等待消费
   System.out.println("已经存满!等待消费。。。。。");
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  this.notify();
  things[counter] = thing;
  counter++;
 }

 public synchronized Thing pop() {
  // 消费
  while (counter == 0) {
   System.out.println("没有产品!等待生产。。。。");
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  this.notify();
  counter--;
  return things[counter];
 }
}

class Producer implements Runnable {
 Stack stack;
 int level;// 生产水平

 public Producer(Stack stack, int level) {
  this.stack = stack;
  this.level = level;
 }

 public void run() {
  for (int i = 0; i <= level; i++) {
   Thing thing = new Thing(i);
   stack.push(thing);
   System.out.println("生产: " + thing.id);
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

class Consumer implements Runnable {
 Stack stack;
 int level;// 消费水平

 public Consumer(Stack stack, int level) {
  this.stack = stack;
  this.level = level;
 }

 public void run() {
  for (int i = 0; i <= level; i++) {
   Thing thing = stack.pop();
   System.out.println("消费: " + thing.id);
   try {
    Thread.sleep(800);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

public class ProducterConsumer {
 public static void main(String[] args) {
  int stackSize = 5;

  Stack stack = new Stack(stackSize);
  // 存储量为5的容器
  Producer p = new Producer(stack, 10);
  Consumer c = new Consumer(stack, 10);
  new Thread(p).start();
  new Thread(c).start();
 }
}

posted on 2009-10-12 17:31 李云泽 阅读(128) 评论(0)  编辑  收藏 所属分类: 面试笔试相关的


只有注册用户登录后才能发表评论。


网站导航: