您的位置:首页 > 其它

同步线程--生产者与消费者模式

2006-10-18 14:51 169 查看
同步线程的一种经典设计模式。

public class Test {
 public static void main(String[] args) {
  Quene q = new Quene();
  Producter producter = new Producter(q);
  Customer customer = new Customer(q);

  producter.start();
  customer.start();
 }
}

//生产者
public class Producter extends Thread {
 private Quene quene;
 public Producter(Quene quene) {
  this.quene = quene;
 }

 @Override
 public void run() {
  for (int i = 0; i < 10; i++) {
   quene.setItem(i);
   System.out.println("生产者:生产产品" + i);
  }
 }
}

//消费者
public class Customer extends Thread {
 private Quene quene;

 public Customer(Quene quene) {
  this.quene = quene;
 }

 @Override
 public void run() {
  for (int i = 0; i < 10; i++) {

   System.out.println("消费者:获得产品" + quene.getItem());
  }
 }
}

//销售列队
public class Quene {
 private int item;
 private boolean isFull = false;
 
 public synchronized int getItem() {
  if (!isFull) {
   try {
    wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  isFull = false;
  this.notify();
  return item;
 }
 
 //因为使用notify()所有要加上 synchronized
 //synchronized 对方法修饰的时候等同与
 // synchronized(this){  ......  }
 public synchronized void setItem(int item) {
  if (!isFull) {
   this.item = item;
   isFull = true;
   this.notify();
  }
  try {
   this.wait();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐