package com.multithreading.pc68; /** * Created by nanzhou on 2017/6/29. */ public class MyObject { private static MyObject myObject = new MyObject(); private MyObject (){ } public static MyObject getInstance(){ //本版本为立即加载 缺点是不能有其他变量 //因为getInstance() 方法没有同步 可能存在非线程安全的问题 return myObject; }}
package com.multithreading.pc68; /** * Created by nanzhou on 2017/6/29. */ public class MyThread extends Thread { @Override public void run() { System.out.println(MyObject.getInstance().hashCode()); } }package com.multithreading.pc68; /** * Created by nanzhou on 2017/6/29. */ public class Run { public static void main(String[] args) { MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); MyThread myThread3 = new MyThread(); myThread1.start(); myThread2.start(); myThread3.start(); } }
单例模式 (一) 立即加载/"饿汉模式"
最新推荐文章于 2025-02-19 10:33:28 发布