package com.线程.死锁;
public class DeadLockSleep {
public static void main(String[] args) {
Object A = new Object();
Object B = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (A) {
System.out.println("t1 getLock A");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
System.out.println("t1 getLock B");
}
}
System.out.println("t1 end");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (B) {
System.out.println("t2 getLock B");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A) {
System.out.println("t2 getLock A");
}
}
System.out.println("t2 end");
}
});
t1.start();
t2.start();
}
}
运行如下:

饿汉式在类加载时就实例化了,使用时直接调用 getInstance() 方法。这个模式为线程安全的,在多线程并发模式下不会重复实例化对象。
class Singleton1 {
private static Singleton1 instance = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() {
return instance;
}
}
这种模式没有在加载时实例化对象,而是在调用getInstance() 方法时实例化对象,使用懒汉式是为了避免过早的实例化,减少内存资源浪费。
class Singleton2 {
private static Singleton2 instance;
private Singleton2() {}
public static Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
}
instance = new Singleton();出现指令重排instance = new Singleton();大致有三个步骤:
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}