模拟两个线程同时访问单例类的情况:
1, 使用了同步方法的单例类SingletonLazyloadSyn.java:
package com.model.Singleton; /* * 单例模式,懒汉式,方法同步 */ public class SingletonLazyloadSyn { /* * 私有的静态的自身类对象 */ private static SingletonLazyloadSyn singleton; /* * 私有的构造方法 */ private SingletonLazyloadSyn(){ } /* * 共有的静态获得实例方法 */ public static synchronized SingletonLazyloadSyn getInstance(){ if(singleton == null){ singleton = new SingletonLazyloadSyn(); } return singleton; } } 2, 测试多线程,判断是否为同一对象ClientSingletonLazyloadSyn.java:
package com.model.Singleton; /* * 测试多线程 */ public class ClientSingletonLazyloadSyn { public static void main(String[] args) { final TreadPair tp = new TreadPair(); /* * 创建两个线程 */ Thread t1 = new Thread(new Runnable(){ public void run(){ tp.setS1(SingletonLazyloadSyn.getInstance()); } }); Thread t2 = new Thread(new Runnable(){ public void run(){ tp.setS2(SingletonLazyloadSyn.getInstance()); } }); /* * 启动线程 */ t1.start(); t2.start(); /* * 加入线程等待 */ try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("相同的对象 ?"+tp.isEquals()); } } 3, 判断单例类对象是否为同一个ThreadPair.java:
package com.model.Singleton; public class TreadPair { SingletonLazyloadSyn s1; SingletonLazyloadSyn s2; public SingletonLazyloadSyn getS1() { return s1; } public void setS1(SingletonLazyloadSyn s1) { this.s1 = s1; } public SingletonLazyloadSyn getS2() { return s2; } public void setS2(SingletonLazyloadSyn s2) { this.s2 = s2; } /* * 判断是否为同一对象 */ public boolean isEquals(){ return s1==s2; } }
运行结果:相同的对象 ?true |