一、在方法上通过synchronized加锁
public class SingleteExample {
private static SingleteExample singleteExample;
private SingleteExample() {
}public synchronized static SingleteExample getInstance() {
if (singleteExample == null) {
singleteExample = new SingleteExample();
}
return singleteExample;
}
}
public class SingleteExample2 {
private static SingleteExample2 singleteExample;
private SingleteExample2() {
}public static SingleteExample2 getInstance() {
if (singleteExample == null) {
synchronized (SingleteExample2.class) {
singleteExample = new SingleteExample2();
}
}
return singleteExample;
}
}
public class SingleteExample3 {
private static SingleteExample3 singleteExample;
private SingleteExample3() {
}
public static SingleteExample3 getInstance() {
if (singleteExample == null) {
synchronized (SingleteExample3.class) {
if (singleteExample == null) {
singleteExample = new SingleteExample3();
}
}
}
return singleteExample;
}
}
public class SingleteExample4 {
private static volatile SingleteExample4 singleteExample;
private SingleteExample4() {
}public static SingleteExample4 getInstance() {
if (singleteExample == null) {
synchronized (SingleteExample4.class) {
if (singleteExample == null) {
singleteExample = new SingleteExample4();
}
}
}
return singleteExample;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |