多线程死锁的原因:
2个以上的线程,互相持有对方需要的锁,都不释放,导致线程都无法继续执行。
引发死锁的前提:
多个线程同时执行
锁不一致
run()中嵌套使用锁
多线程死锁示例:
package com.gc.thread;
public class DeadLock implements Runnable {
private final Object mutex1 = new Object();
private final Object mutex2 = new Object();
boolean flag = true;
public void run() {
if(flag) {
flag = false;
synchronized (mutex1) {
System.out.println("if ... mutex1");
synchronized(mutex2) {
System.out.println("if ... mutex2");
}
}
} else {
synchronized (mutex2) {
System.out.println("eles ... mutex2");
synchronized(mutex1) {
System.out.println("eles ... mutex1");
}
}
}
}
public static void main(String[] args) throws InterruptedException {
DeadLock runnable = new DeadLock();
new Thread(runnable).start();
new Thread(runnable).start();
}
}
相互持有锁,都不释放
if ... mutex1
eles ... mutex2