线程死锁
当线程1持有锁A并申请锁B,而此时有个线程2持有锁B并申请锁A时,就会导致程死锁。这种情况下,除非手动结束java进程否则这两个线程将无法打破僵持状态。
image.png
如何避免死锁
当多个线程都需要申请多个资源时,如果申请资源的顺序都一致, 就能保证任意时刻只能有一个线程可以同时获得所有资源,其他线程必须等当前线程释放所有资源后才能重新获得锁。
image.png
虽然多线程只要以固定顺序请求资源就能避免死锁的发生,但实际业务场景千变万化,很难保证总是处于理想的状态。
死锁检测
只有检测到死锁的状态,才能做针对性的业务处理。
ThreadMXBean是java.lang.management包提供的工具类,通过ThreadMXBean类的findDeadlockedThreads()方法能获得发生死锁的线程编号。
public class DeadLockDemo {
private Object lock1 = new Object();
private Object lock2 = new Object();
public void doActionA() {
synchronized (lock1) {
System.out.println(Thread.currentThread() + ": acquire lock1");
try {
// 线程阻塞,让其他线程拿到lock2
Thread.sleep(10);
} catch (Exception e) {
}
synchronized (lock2) {
System.out.println(Thread.currentThread() + ": acquire lock2");
}
}
}
public void doActionB() {
synchronized (lock2) {
System.out.println(Thread.currentThread() + ": acquire lock2");
synchronized (lock1) {
System.out.println(Thread.currentThread() + ": acquire lock1");
}
}
}
public static void main(String[] args) {
Thread monitorThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
long[] ids = tmx.findDeadlockedThreads();
if (ids != null) {
ThreadInfo[] tmxThreadInfo = tmx.getThreadInfo(ids, true, true);
System.out.println("The following threads are deadlocked:");
for (ThreadInfo ti : tmxThreadInfo) {
System.out.println(ti);
}
break;
}
}
}
});
monitorThread.start();
DeadLockDemo demo = new DeadLockDemo();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
demo.doActionA();
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
demo.doActionB();
}
});
thread1.start();
thread2.start();
}
}
总结
死锁的发生总是很难避免,只能在多线程设计时,尽可能全面的考虑死锁的风险。对于业务要求严格的场景,可以采取必要的死锁检测机制,保证系统的健壮性。
网友评论