死锁是两个线程互相等待对方释放资源。
死锁案例代理如下:
package com.zzh.study;
import java.util.concurrent.locks.ReentrantLock;
public class ProcessDeadLockTest {
ReentrantLock locka ;
ReentrantLock lockb ;
Object obja ;
Object objb ;
public ProcessDeadLockTest(){
locka = new ReentrantLock();
lockb = new ReentrantLock();
obja = new Object();
objb = new Object();
}
public void methodc() {
synchronized (obja){
try {
obja.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (objb){
}
}
}
public void methodd() {
synchronized (objb){
try {
objb.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obja){
}
}
}
public void methoda(){
locka.lock();
try {
Thread.sleep(400L);
methodb();
} catch (InterruptedException e) {
e.printStackTrace();
}
locka.unlock();
}
public void methodb(){
lockb.lock();
try {
Thread.sleep(500L);
methoda();
} catch (InterruptedException e) {
e.printStackTrace();
}
lockb.unlock();
}
}
package com.zzh.study;
public class Test {
public static void main(String[] args) {
ProcessDeadLockTest pt = new ProcessDeadLockTest();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("====run1====");
pt.methodc();
//pt.methoda();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("====run2====");
pt.methodd();
//pt.methodb();
}
});
System.out.println("====start===");
t1.start();
t2.start();
System.out.println("=====end====");
}
}
methoda 和 methodb 的死锁很容易发现:
jstack -l 5573
methodc 和 methodd 不是那么容易发现,一般情况先搜索下locked关键字,然后结合实际代码分析被锁的原因: