码迷,mamicode.com
首页 > 其他好文 > 详细

生产消费锁---信号灯模式

时间:2015-04-03 14:51:18      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

package com.Thread;
 
public class Custom_Producer {
       public static void main(String[] args) {
             //共享资源
            Production pro = new Production();
            
            Custom custom = new Custom(pro);
            Producer producer = new Producer(pro);
             new Thread(producer).start();
             new Thread(custom).start();
      }
}
//资源
class Production {
       private String src ;
       /**
       * 信号
       * flag ---> true  生产,消费等待, 生产完成,通知消费
       * flag ---> false  消费,生产等待,  消费完成,通知生产
       */
       private boolean flag = true;
      
       public synchronized void product(String src) throws Exception{
             if(!flag ) {// false 生产等待
                   this.wait();
            }
             //开始生产
            Thread. sleep(500);
             //生产完毕
             this.src = src;
            System. out.println("生产了----------->" + src);
             //通知消费
             this.notify();
             //停止生产
             this.flag = false;
      }
      
       public synchronized void custom() throws Exception {
             if(flag ) {// true 消费等待
                   this.wait();
            }
             //开始消费
            System. out.println("消费了---" +src );
             //消费完毕
             //通知生产
             this.notifyAll();
             //停止消费
             this.flag = true;
      }
}
//生产
class Producer implements Runnable {
      Production p ;
      
       public Producer(Production p) {
             this.p = p;
      }
       @Override
       public void run() {
             for(int i=0; i<20; i++) {
                   if(0==i%2) {
                         try {
                               p.product( "奇数====生产了" + i +" 个");
                        } catch (Exception e) {
                              e.printStackTrace();
                        }
                  } else {
                         try {
                               p.product( "偶数====生产了" + i +" 个");
                        } catch (Exception e) {
                              e.printStackTrace();
                        }
                  }
            }
      }
      
}
//消费
class Custom implements Runnable {
      Production p ;
 
       public Custom(Production p) {
             this.p = p;
      }
       @Override
       public void run() {
             for(int i=0; i<20; i++) {
                   try {
                         p.custom();
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }
}

生产消费锁---信号灯模式

标签:

原文地址:http://www.cnblogs.com/king-/p/4389734.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!