ITPub博客

首页 > IT职业 > IT职场 > 工厂模式

工厂模式

IT职场 作者:lhx1976 时间:2021-09-09 09:48:08 0 删除 编辑

public class Test {

   

    public static void main(String[] args){

        Object mutex = new Object();

        new Producer(mutex).start();

        new Consumer(mutex).start();

    }

   

    static class Product{

        public volatile static String value = null;

    }

   

    static class Consumer extends Thread{

        private  Object mutex;

        public Consumer(Object mutex) {

            this.mutex = mutex;

        }

        @Override

        public void run() {

            //一直消费产品

            while (true){

               synchronized (mutex){

                   //如果还没生产出产品 等待生产出产品

                   if (null == Product.value){

//                    System.out.println("consumer :"+Product.value);

//                    Product.value = null;

                       try {

                           mutex.wait();

                       } catch (InterruptedException e) {

                           e.printStackTrace();

                       }

                   }

                   //使用

                   System.out.println("consumer :"+Product.value);

                   Product.value = null;

                   //通知生产者 可以生产了

                   mutex.notify();

               }

            }

        }

    }

   

    static class Producer extends Thread{

        private  Object mutex;

        public Producer(Object mutex) {

            this.mutex = mutex;

        }

        @Override

        public void run() {

            //生产 产品

            while (true){

                synchronized (mutex){

                    //如果没有产品就生产

                    if (null != Product.value){

                        try {

                            mutex.wait();

                        } catch (InterruptedException e) {

                            e.printStackTrace();

                        }

                    }

                    Product.value = "NO:"+System.currentTimeMillis();

                    System.out.println("producer ");

                    //通知消费者 可以消费了

                    mutex.notify();

                }

            }

        }

    }

}

原文链接:http://www.apkbus.com/blog-340477-76911.html

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4414/viewspace-2812642/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    0
  • 访问量
    452