生产者-消费者模式 系列 之一 Sychronized,Notify,Wait 篇

生产者,消费者模式可谓是Java多线程中比较经典的例子.该系列文章希望以该模式的实现为起点,将Java中对于多线程同步和通讯技术做一个总结.这第一个坑肯定要留给包括 Sychronized , Notify,和Wait 方法.关于这几个技术点的介绍,网上一搜一大把,这里不多说.只是把我自己学习过程中的一些理解难点做个说明,希望对看到这篇文章的人有所帮助.
Sychronized : 知道锁一般包括类级锁和对象级锁.锁类型不同,结果也是不同的. 实验一下下面的代码就知道了.看注释.

public class SynchronziedTest {  
  
    public static void main(String[] args){  
        C c1 = new C(new Share(),"Consumer01");//注意,这里每个线程有不同的Share实例.  
        C c2 = new C(new Share(),"Consumer02");  
        C c3 = new C(new Share(),"Consumer03");  
        P p1 = new P(new Share(),"Producer01");  
        c1.start();  
        c2.start();  
        c3.start();  
        p1.start();  
          
    }  
}  
class Share{  
      
    private static int i;  
    private final static Object _lock = new Object();  
      
    public void add(){  
        synchronized(this._lock){  //将此处改为this.getClass()效果相同,因为他们获得的是类级锁.更改为this就错了,它获得是对象锁.   
          ++i;  
          System.out.println(Thread.currentThread().getName() + " Remaining Size = " + i);  
        }  
          
    }  
    public void get(){  
        synchronized(this._lock){ //将此处改为this.getClass()效果相同,因为他们获得的是类级锁.更改为this就错了,它获得是对象锁.            if (i > 0){  
                try {  
                    Thread.sleep(1000); //让线程睡会,更改为synchronized(this)后,增大别的线程(i>0)为true 的机会.  
                } catch (InterruptedException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
                --i;  
                System.out.println(Thread.currentThread().getName() + " Remaining Size = " + i);  
            }  
              
        }  
    }  
}  
class C extends Thread{  
    private Share _repository;  
    public C(Share s,String threadName){  
        super(threadName);  
        this._repository = s;  
    }  
    public void run() {  
         while(true){  
             this._repository.get();  
             try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
         }  
    }  
}  
  
class P extends Thread{  
    private Share _repository;  
    public P(Share s,String threadName){  
        super(threadName);  
        this._repository = s;  
          
    }  
    public void run() {  
        while(true){  
            this._repository.add();  
            try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
    }  
}  

Wait : 阻塞当前持有调用该方法的对象的锁的线程,并释放锁.当被同一个对象的notify方法唤醒时,只有获得CPU资源后,该线程将从调用wait方法执行点继续执行.
Notify : 通知被同一个对象的wait方法所阻塞的一个线程.使其在获得CPU资源后从上次的执行点(即wait方法处)继续执行.

  • 生产者消费者场景假定
  • 同时只能有一个生产者进行生产.生产的同时,不能有消费者在消费.
  • 同时只有一个消费者在消费.消费的同时,不能有生产者生产.
  • 生产者最多能生产10个产品. 如果当前产品数超过10个,生产者将等待直到产品数小于10才开始生产.
  • 当前如果没有可消费产品时,消费者将等待直到有产品可消费为止.
import java.util.Stack;  
  
public class TypicalCPTest {  
  
  
    public static void main(String[] args) {  
          
        Repository s = new Repository();  
        Maker f1 = new Maker(s,"P001");  
        Maker f2 = new Maker(s,"P002");  
          
        f1.start();  
        f2.start();  
  
        Taker c1 = new Taker(s,"C001");  
        Taker c2 = new Taker(s,"C002");  
        Taker c3 = new Taker(s,"C003");  
        c1.start();  
        c2.start();  
        c3.start();  
          
    }  
  
}  
class Repository{  
      
    private  final static int MAX_ELEMENT = 10;  
      
    private Stack<String> _store = new Stack<String>();  
      
    public  void add(String in) throws InterruptedException{  
          
        synchronized(this){  
            while (this._store.size() >= MAX_ELEMENT) {  
                System.out.println(Thread.currentThread().getName() + " is waiting on add.");  
                this.wait(); //如果参数中数量达到10个的最大值.生产者线程等待.  
                System.out.println(Thread.currentThread().getName() + " is after waiting on add.");  
            }  
            this._store.push(in);  
            System.out.println(Thread.currentThread().getName() + " is adding product "+ in+". Remaining size is "+ this._store.size());  
            this.notify(); //唤醒那些因为产品库为零时等待的消费者进程.  
        }  
  
  
    }  
      
    public   String  get() throws InterruptedException{  
        String rtn = "";  
        synchronized(this){  
            while (this._store.isEmpty()) {  
                System.out.println(Thread.currentThread().getName() + " is waiting on get.");  
                this.wait();//如果产品库为空,消费者线程等待.直到产品库中有产品时被唤醒.  
                System.out.println(Thread.currentThread().getName() + " is after waiting on get.");  
                  
            }  
              
            rtn = this._store.pop();  
            System.out.println(Thread.currentThread().getName() + " is getting product "+ rtn+". Remaining size is "+ this._store.size());  
            this.notify();//唤醒因产品库为空可能导致等待的生产者线程.  
        }  
        return rtn;  
    }  
  
}  
  
class Maker implements Runnable {  
         
    private Repository _store;  
    private String _name;  
    private Thread _thread;  
    public Maker(Repository s,String name) {  
    super();  
    this._store = s;  
    this._name = name;  
    this._thread = new Thread(this,name);  
    }  
      
    public void start(){  
        this._thread.start();  
    }  
      
    @Override  
    public void run() {  
        int i = 0;  
        while(true){  
            try {  
                this._store.add(this._name + " Product "+ ++i);  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            } catch (Exception e){  
                e.printStackTrace();  
            }  
        }  
  
    }  
  
}  
  
  
class Taker implements Runnable {  
        
    private Repository _store;  
    private Thread _thread;  
    public Taker(Repository s,String name) {  
        super();  
        this._store =s;  
        this._thread = new Thread(this,name);  
    }  
    public void start(){  
        this._thread.start();  
    }  
      
    @Override  
    public void run() {  
        while(true){  
            try {  
                this._store.get();  
                Thread.sleep(5000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
    }  
  
}  

运行结果:

P001 is adding product P001 Product 1. Remaining size is 1  
C001 is getting product P001 Product 1. Remaining size is 0  
P002 is adding product P002 Product 1. Remaining size is 1  
C003 is getting product P002 Product 1. Remaining size is 0  
C002 is waiting on get.  
P002 is adding product P002 Product 2. Remaining size is 1  
C002 is after waiting on get.  
C002 is getting product P002 Product 2. Remaining size is 0  
P001 is adding product P001 Product 2. Remaining size is 1  
P001 is adding product P001 Product 3. Remaining size is 2  
P002 is adding product P002 Product 3. Remaining size is 3  
P002 is adding product P002 Product 4. Remaining size is 4  
P001 is adding product P001 Product 4. Remaining size is 5  
P001 is adding product P001 Product 5. Remaining size is 6  
P002 is adding product P002 Product 5. Remaining size is 7  
P001 is adding product P001 Product 6. Remaining size is 8  
P002 is adding product P002 Product 6. Remaining size is 9  
C003 is getting product P002 Product 6. Remaining size is 8  
C001 is getting product P001 Product 6. Remaining size is 7  
C002 is getting product P002 Product 5. Remaining size is 6  
P002 is adding product P002 Product 7. Remaining size is 7  
P001 is adding product P001 Product 7. Remaining size is 8  
P002 is adding product P002 Product 8. Remaining size is 9  
P001 is adding product P001 Product 8. Remaining size is 10  
P001 is waiting on add.  
P002 is waiting on add.  
C001 is getting product P001 Product 8. Remaining size is 9  
P001 is after waiting on add.  
P001 is adding product P001 Product 9. Remaining size is 10  
P002 is after waiting on add.  
P002 is waiting on add.  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,273评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,349评论 3 398
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,709评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,520评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,515评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,158评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,755评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,660评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,203评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,287评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,427评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,122评论 5 349
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,801评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,272评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,393评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,808评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,440评论 2 359

推荐阅读更多精彩内容