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

     

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

  • 相关阅读:
    Java打印M图形(二维数组)——(九)
    Java调整JVM内存大小——(八)
    Java导出List集合到txt文件中——(四)
    Java读取Txt封装到对象中——(三)
    Java读取txt文件——(二)
    Java导出txt模板——(一)
    c# listview导出excel文件
    mfc 导出数据保存成excel和txt格式
    数据库日志删除重建方法
    HTTP POST请求的Apache Rewrite规则设置
  • 原文地址:https://www.cnblogs.com/wxwall/p/3445380.html
Copyright © 2011-2022 走看看