線程死鎖
當(dāng)線程1持有鎖A并申請(qǐng)鎖B功咒,而此時(shí)有個(gè)線程2持有鎖B并申請(qǐng)鎖A時(shí)愉阎,就會(huì)導(dǎo)致程死鎖绞蹦。這種情況下力奋,除非手動(dòng)結(jié)束java進(jìn)程否則這兩個(gè)線程將無法打破僵持狀態(tài)。
如何避免死鎖
當(dāng)多個(gè)線程都需要申請(qǐng)多個(gè)資源時(shí)幽七,如果申請(qǐng)資源的順序都一致景殷, 就能保證任意時(shí)刻只能有一個(gè)線程可以同時(shí)獲得所有資源,其他線程必須等當(dāng)前線程釋放所有資源后才能重新獲得鎖澡屡。
雖然多線程只要以固定順序請(qǐng)求資源就能避免死鎖的發(fā)生猿挚,但實(shí)際業(yè)務(wù)場(chǎng)景千變?nèi)f化,很難保證總是處于理想的狀態(tài)驶鹉。
死鎖檢測(cè)
只有檢測(cè)到死鎖的狀態(tài)绩蜻,才能做針對(duì)性的業(yè)務(wù)處理。
ThreadMXBean是java.lang.management包提供的工具類室埋,通過ThreadMXBean類的findDeadlockedThreads()方法能獲得發(fā)生死鎖的線程編號(hào)办绝。
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();
}
}
總結(jié)
死鎖的發(fā)生總是很難避免姚淆,只能在多線程設(shè)計(jì)時(shí)孕蝉,盡可能全面的考慮死鎖的風(fēng)險(xiǎn)。對(duì)于業(yè)務(wù)要求嚴(yán)格的場(chǎng)景腌逢,可以采取必要的死鎖檢測(cè)機(jī)制降淮,保證系統(tǒng)的健壯性。