模拟多线程通信

package com.mackstone.Thread;
/**
 * @实现了多线程之间的通信
 * @author MackStone
 * @模拟。。。。。
 */
public class ThreadCommenterThir {
   public static void main(String[] args){
  Goods gds = new Goods();
  new Thread(new Produce(gds)).start();
  new Thread(new Consume(gds)).start();
 } 
}
//生产产品类
class Produce implements Runnable{
 
 Goods goods;
 public Produce(Goods goods){
  this.goods = goods;
 }
 public void run(){
  int i =0;
  while(true){
   if(i ==0){
    goods.put("电冰箱", "家电");
   }else{
    goods.put("卡车", "运输类");
   }
   i = (i+1)%2; //使变量i在1~2之间
  }
 }
}
//消费产品类
class Consume implements Runnable{
 
 Goods goods;
 public Consume(Goods goods){
  this.goods = goods;
 }
 public void run(){
  while(true){
   goods.get();
  }
 }
}
//产品类
class Goods{
 private String goodsName ;
 private String goodsAttrubite;
 private boolean bFull = false;  //信号量。。。控制线程用
 
 //生产产品的方法
 public synchronized void put(String name,String attrubite){
  
  if(bFull)    //如果还没有生产产品。。。那么现在就开始生产一种产品
   try {
    wait(); //如果货物没取走。。让线程执行等待。。。。。。
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  this.goodsName = name;
  this.goodsAttrubite = attrubite;
  
  bFull = true;   //生产一种产品后告诉缓冲区。消费者可以去取货了。。。
  notify();  //唤醒消费者的等待线程。可以去取货了。
 }
 
 //消费产品的方法
 public synchronized void get(){
  
  if(!bFull) //判断缓冲区中是否有货物。。如果有(true)就取货。。不要进行等待操作;如果没有(false)线程就继续等待
   try {
    wait(); //在缓冲区中没有货的情况下。。线程进行等待。。。。。。。
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  System.out.println("产品名: "+goodsName);
  System.out.println("产品属性: "+goodsAttrubite);
  System.out.println("------------------------");
  
  bFull = false;   //缓冲区中的货物取走了。。。
  notify();   //唤醒生产者的等待线程。。让它进行生产货物。。。。。
 }
}

你可能感兴趣的:(职场,休闲,模拟多线程通信)