java 实现生产消费

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011066470/article/details/86560861

知识点:多线程之间的通信;

代码:



public class Resources {
    public static int count=0;
    public static boolean flag=false;
}



public class Producer  implements  Runnable {
    public Resources res;
    public Producer(Resources res) {
        this.res=res;
    }

    @Override
    public void run() {
        while(true){
            synchronized (res){
                while(res.flag){
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
               res.count= res.count+1;
                System.out.println(Thread.currentThread().getName()+"我是生产者,生产第"+res.count+"个产品");
                res.flag=true;
                res.notifyAll();

            }
        }
    }
}



public class Consumer implements Runnable{
    public Resources res;
    public Consumer(Resources res) {
        this.res=res;
    }

    @Override
    public void run() {
        while(true){
            synchronized (res){
                while(!res.flag){
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName()+"我是消费者,正在消费第:"+res.count+"个");
                res.flag=false;
                res.notifyAll();

            }
        }
    }
}



public class Test {
    public static void main(String args[]){
      Resources res=new Resources();
      new Thread(new Producer(res),"p1").start();
      new Thread(new Producer(res),"p2").start();
       new Thread(new Consumer(res),"c1").start();
        new Thread(new Consumer(res),"c2").start();
    }
}

执行结果:

都看到这里了,就顺手点击左上角的【关注】按钮,点击右上角的小手,给个评论,关注一下,再走呗!☺

猜你喜欢

转载自blog.csdn.net/u011066470/article/details/86560861