饿汉式和懒汉式都是线程安全的,怎么说呢?
// hungry style 饿汉式
public class Test4 {
private static Test4 instance = new Test4();
private Test4(){
}
public Test4 getInstance(){
return instance;
}
}
懒汉式
// lazy man style
public class Test5 {
private static Test5 instance;
private Test5(){
}
// need to be synchronized;
public static synchronized Test5 getInstance(){
if(null == instance)
instance = new Test5();
return instance;
}
}
|
|