DCL双检查锁机制
双检查锁就是在同步代码块调用之前检查一遍,载再在同步代码块内部再检查一遍。双重保险
public class ServiceA {
private volatile static ServiceA service;
private ServiceA(){
}
public stati<span id="_xhe_cursor"></span>c ServiceA getInstance(){
try{
if(service != null){
}else{
Thread.sleep(3000);
synchronized(ServiceA.class){
if(service == null){
service = new ServiceA();
}
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
return service;
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
public void run(){
System.out.println(ServiceA.getInstance().hashCode());
}
}