rol*_*luo 1 java multithreading
静态方法和变量:
public class Singleton{
private static Singleton singleton = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(singletion == null)
singleton = new Singletion();
return singleton;
}
}
Run Code Online (Sandbox Code Playgroud)
Java 1.5 之后的第二个
public class Singleton{
private static volatile Singleton singleton = null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
synchronized(this){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
Run Code Online (Sandbox Code Playgroud)
那么这两个线程安全代码的优缺点是什么,我们什么时候应该使用哪个呢?
第二个是线程安全的,但以下更简单,更快,因为它不需要同步块。
public enum Singleton {
INSTANCE;
// define fields and methods here.
}
Run Code Online (Sandbox Code Playgroud)
访问
Singleton.INSTANCE.method();
Run Code Online (Sandbox Code Playgroud)
注意:如果需要,枚举可以实现接口。