标签:sha vpd 测试 初始 ++ package 初始化 技术 同步
什么是单例模式?懒汉式(线程不安全)
?
public class Singleton {
private static Singleton singleton;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return singleton;
}
}
单例模式的注意事项
?
高并发的情况下注意单例模式的线程同步问题,测试代码如下:
?
public class Emperor {
private static String name = null;
private static Emperor emperor = null;
//限制产生多个对象
private Emperor(String e) {
Emperor.name=e;
}
//通过该方法获得实例对象
public static Emperor getInstance(String e) {
if (emperor == null) {
emperor = new Emperor(e);
}
return emperor;
}
//类中的其他方法尽量使用static
public static void say(String m) {
// Emperor.name=e;
System.out.println("我是:"+ m +", 参见皇帝"+Emperor.name);
}
}
?
package com.zgz.dm.Singleton;
public class Minister {
public static void main(String[] args) {
Minister1 minister1 = new Minister1();
Minister2 minister2 = new Minister2();
new Thread(minister1).start();
new Thread(minister2).start();
/*for(int day=0; day<3; day++) {
Emperor emperor = Emperor.getInstance();
emperor.say();
}*/
}
}
class Minister1 implements Runnable{
private String minister = "王安石";
private String s = "宋神宗1";
@Override
public void run() {
for(int i=0; i<10; i++) {
Emperor emperor = Emperor.getInstance();
emperor.say(s,minister);
try {
Thread.sleep((int)Math.random()*200);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Minister2 implements Runnable{
private String minister = "苏轼";
private String s = "宋神宗2";
@Override
public void run() {
for(int i=0; i<10; i++) {
Emperor emperor = Emperor.getInstance();
emperor.say(s,minister);
try {
Thread.sleep((int)Math.random()*1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
?
测试结果:
?
?
原因分析:
?
王安石应该是宋神宗1啊?为啥是宋神宗12呢,就说明内存中存在两个对象。一个线程A执行到 emperor = new Emperor(),但还没有获得对象(对象的初始化需要时间),第二个线程B正在执行,执行到 (emperor == null),线程B获得判断条件为真,于是继续执行。于是A与B都获得了对象,内存中出现了两个对象。
?
解决办法:
?
加锁,执行效率低。建议使用饿汉式单例
标签:sha vpd 测试 初始 ++ package 初始化 技术 同步
原文地址:http://blog.51cto.com/13416247/2296494