一、使用synchronized 和 Thread.sleep()写一个简单的死锁
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;
}
}
四、双重校验锁
- 使用volitile关键字防止最里面的
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;
}
}