当前位置: 移动技术网 > IT编程>开发语言>Java > Java多线程中的单例模式两种实现方式

Java多线程中的单例模式两种实现方式

2019年07月22日  | 移动技术网IT编程  | 我要评论

java多线程中的单例模式

一、在多线程环境下创建单例

方式一:

package com.ietree.multithread.sync;

public class singletion {
  
  private static class innersingletion {
    private static singletion single = new singletion();
  }

  public static singletion getinstance() {
    return innersingletion.single;
  }
}

方式二:

package com.ietree.multithread.sync;

public class dubblesingleton {

  private static dubblesingleton ds;

  public static dubblesingleton getds() {
    if (ds == null) {
      try {
        // 模拟初始化对象的准备时间...
        thread.sleep(3000);
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
      synchronized (dubblesingleton.class) {
        if (ds == null) { // 这个判断很重要,如果没有那将不是单例,而是多例
          ds = new dubblesingleton();
        }
      }
    }
    return ds;
  }

  public static void main(string[] args) {
    
    thread t1 = new thread(new runnable() {
      @override
      public void run() {
        system.out.println(dubblesingleton.getds().hashcode());
      }
    }, "t1");
    
    thread t2 = new thread(new runnable() {
      @override
      public void run() {
        system.out.println(dubblesingleton.getds().hashcode());
      }
    }, "t2");
    
    thread t3 = new thread(new runnable() {
      @override
      public void run() {
        system.out.println(dubblesingleton.getds().hashcode());
      }
    }, "t3");

    t1.start();
    t2.start();
    t3.start();
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网