利用wait 与notifyAll 方法进行演示生产与消费的模式的演示,我们两个线程负责生产,两个线程消费,只有生产了才能消费:

 在effective Java 中有说过:

    1. 在Java 中 ,使用wait() 方法,你99% 情况都是要和while 连用

    2. 永远都要使用notifyAll() 而不是notify();

 

package com.java.baseknowledge.concurrent.thread;

/**
 * Thread class  and Object  method recommend:
 *  provider and customer use wait() and notify() method
 * @author iscys
 *
 */
public class ThreadMethod {

    public static void main(String[] args) {
        Sample sample =new Sample();
        Increase in =new  Increase(sample);
        Decrease de =new  Decrease(sample);
        Thread th1 =new Thread(in);
        Thread th2 =new Thread(de);
        
        
        Increase in1 =new  Increase(sample);
        Decrease de1 =new  Decrease(sample);
        Thread th11 =new Thread(in1);
        Thread th21 =new Thread(de1);
        th1.start();
        th2.start();
        th11.start();
        th21.start();
    }

}
/**
 * increase thread
 * @author cys
 *
 */
class Increase implements Runnable{
    
    private Sample sample;
    public Increase(Sample sample) {
        this.sample=sample;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        try {
            sample.increase();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }
}

class Decrease implements Runnable{
    
    private Sample sample;
    public Decrease(Sample sample) {
        this.sample=sample;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++)
        {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            
        try {
            sample.decrease();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }
}
class Sample{
    
    private int i;
    
    public synchronized void increase() throws Exception {
        /**使用while 可以每次检查,不能使用if ,会造成问题,什么样的问题,把while 改成if 试试看**/
        while(0!=i) {
            this.wait();
        }
        i++;
        System.out.println(i);
        this.notifyAll();
    }
    
    public synchronized void decrease() throws Exception {
        /**使用while 可以每次检查,不能使用if ,会造成问题,什么样的问题,把while 改成if 试试看**/
        while(0==i) {
            this.wait();
        }
        i--;
        System.err.println(i);
        this.notifyAll();
    }
}

 

posted on 2018-09-28 19:39  iscys  阅读(182)  评论(0编辑  收藏  举报