zoukankan      html  css  js  c++  java
  • Static 单例模式

    Static 方法的问题

    今天在看EhCache源码的时候,发现有一个这样的方法

     

    这个是个典型的单例模式的工具类,但我所知道的单例模式的写法不是这样的,虽然《effect java》中推荐的方法是用枚举,static方法类似于枚举方法,但觉得这种单例模式确实值得学习学习。

     

    看我的测试结果:

    总共两个类

    /**

    * 测试单例类

    * @author wu

    *

    */

    public class StaticClass {

        

        public static Integer id = 0;

        

        private StaticClass(){

            

        }

        

        public static void sysInfo(){

            System.out.println("this is " + id);

            id++;

        }

    }

     

     

     

    第二个类

    package com.test;

     

    /**

    * 测试类

    * @author wu

    *

    */

    public class TestMain {

     

        public static void main(String[] args) {

            test();

        }

        

        /**

         * 调用3次数,输出结果

         */

        public static void test(){

            for (int i = 0; i < 3; i++) {

                StaticClass.sysInfo();

            }

        }

     

        /**

         * 多线程调用

         */

        public static void runIt(){

            for (int i = 0; i < 4; i++) {

                new Thread(new Runnable() {

                    @Override

                    public void run() {

                        StaticClass.sysInfo();

                    }

                }).start();

            }

        }

    }

     

    第一次测试结果:

    this is 0

    this is 1

    this is 2

     

    这个结果证明每调用static方法,都不会产生新的实例,所以,符合单例模式的需求。是不是这样就可以直接说这个是单例模式了?

    再看下面的多线程测试结果:

    this is 0

    this is 0

    this is 0

    this is 0

     

    这个结果产生的是4个不同的实例,所以上面的方法在多线程情况下是结果是不对的,不符合单例模式的需求。但有没有办法解决这种情况了?

    答案是有的,多线程模式事以同步,加个关键字

    public synchronized static void sysInfo(){

            System.out.println("this is " + id);

            id++;

        }

    测试结果:

     

    this is 0

    this is 1

    this is 2

    this is 3

     

    这样在多线程环境下也可以实现单例模式,这个方法确实比以前的单例模式好的地方,就是不需要在私有构造器中创建对象。也不需要担心多线程情况下出现其他错误情况!

  • 相关阅读:
    Magento速度优化
    magento-connect-manage出现404或者500内部错误的解决办法
    magento -- 给后台分类管理页的分类商品加一栏商品类型
    magento -- 添加新产品时状态默认为激活,库存状态默认为有库存
    magento -- 如何为商品分类(category)添加自定义属性
    magento -- 如何改善前台图片质量
    安装Let's Encrypt SSL证书
    centos版本查看
    ps
    设置桥接虚拟网卡
  • 原文地址:https://www.cnblogs.com/wxwall/p/3445380.html
Copyright © 2011-2022 走看看