天天看點

同步線程--生産者與消費者模式

同步線程的一種經典設計模式。

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 {

 public Customer(Quene quene) {

   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) {

   this.item = item;

   isFull = true;

   this.notify();

  try {

   this.wait();

  } catch (InterruptedException e) {

   e.printStackTrace();

繼續閱讀