歡迎您光臨本站 註冊首頁

Java線程;生產消費者例子

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

  小小回顧.寫了個簡單的demo..項目中沒有過 還能記得,紀念一下..

  產品的entity..

  Java代碼

  public class Product {

  //產品名稱

  private String name;

  public String getName() {

  return name;

  }

  public void setName(String name) {

  this.name = name;

  }

  }

  生產者

  Java代碼

  /**

  * 生產者

  * @author 飯香

  *

  */

  public class Producer implements Runnable{

  private Shop shop;//要去送貨的商店

  public Producer(Shop shop){

  this.shop=shop;

  }

  public void run() {

  for(int i=0;i<100;i ){

  shop.produ();

  }

  }

  }

  消費者

  Java代碼

  /**

  * 消費者

  * @author 飯香

  *

  */

  public class Cousumer implements Runnable{

  private Shop shop;//要去消費的商店

  public Cousumer(Shop shop){

  this.shop=shop;

  }

  public void run() {

  for(int i=0;i<100;i ){//消費100次

  shop.cousu();

  }

  }

  }

  模擬商店(一切圍繞商店,商店只能有一個,產品隨便多個實例.這個也是別人問我總是出錯的地方.對象思想)

  Java代碼

  import java.util.ArrayList;

  import java.util.List;

  /**

  * 模擬商店 (進貨/銷售)

  * @author fx

  *

  */

  public class Shop {

  private static int i=0;

  //產品的容器;達到容器暫停生產,消費到0等待生產

  private static List<Product> list;

  static{

  list= new ArrayList<Product>();

  }

  /**

  * 生產產品

  */

  public synchronized void produ(){

  if(list.size()>=5){

  try {

  System.out.println("--------------生產商品" i "時,達到了總數暫停生產-------");

  this.wait();//進入休眠

  } catch (InterruptedException e) {

  System.out.println(e.toString());

  e=null;

  }

  } //生產商品

  Product product= new Product();

  product.setName("商品" i);

  list.add(product);

  System.out.println("生產了商品---->" product.getName() "商品總數" i);

  System.out.println("容器容量" list.size());

  i ;

  super.notify();

  }

  /**

  * 消費產品

  * @return

  */

  public synchronized void cousu(){

  if(list.size()==0){//消費完時,掛起

  System.out.println(" 商品消費完了.等待 =");

  try {

  this.wait();

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  System.out.println(e.toString());

  e=null;

  }

  }

  Product product=list.get(0);

  list.remove(0);

  System.out.println("消費了獲得了商品-->" product.getName());

  System.out.println("容器容量" list.size());

  super.notify();

  }

  }

  測試代碼

  Java代碼

  public static void main(String[] args) {

  Shop shop=new Shop();//商店

  Producer pro=new Producer(shop);

  Cousumer cou = new Cousumer(shop);

  new Thread(pro,"pro").start();

  new Thread(cou,"cou").start();

  }

  生產了商品---->商品93商品總數93

  容器容量1

  消費了獲得了商品-->商品93

  容器容量0

   商品消費完了.等待 =

  生產了商品---->商品94商品總數94

  容器容量1

  消費了獲得了商品-->商品94

  容器容量0

   商品消費完了.等待 =

  生產了商品---->商品95商品總數95

  容器容量1

  消費了獲得了商品-->商品95

  容器容量0

   商品消費完了.等待 =

  生產了商品---->商品96商品總數96

  容器容量1

  生產了商品---->商品97商品總數97

  容器容量2

  消費了獲得了商品-->商品96

  容器容量1

  生產了商品---->商品98商品總數98

  容器容量2

  消費了獲得了商品-->商品97

  容器容量1

  生產了商品---->商品99商品總數99

  容器容量2

  消費了獲得了商品-->商品98

  容器容量1

  消費了獲得了商品-->商品99

  容器容量0


[火星人 ] Java線程;生產消費者例子已經有644次圍觀

http://coctec.com/docs/java/show-post-60164.html