在JAVA中使用DCL双检查锁机制实现单例的多线程安全

元旦放假期间学代码,我都感动我自己啦。

试过了,OK的。



package demo.thread;

public class MyObject {
	private static MyObject myObject ;
	private MyObject() {
		
	}
	public static MyObject getInstance() {
		try {
			if (myObject != null){
				
			} else {
				Thread.sleep(3000L);
				synchronized (MyObject.class) {
					if (myObject == null){
						myObject = new MyObject();
					}
					
				}
				
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		return myObject;
	}

}


package demo.thread;

public class MyThread extends Thread {
	@Override
	public void run() {
		System.out.println(MyObject.getInstance().hashCode());
	}

}


package demo.thread;

public class Run {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread t1 = new MyThread();
		t1.start();
		
		MyThread t2 = new MyThread();
		t2.start();

		
		MyThread t3 = new MyThread();
		t3.start();


	}

}

在JAVA中使用DCL双检查锁机制实现单例的多线程安全
上一篇:习题3.13


下一篇:android adb push 与 adb install的比较