Introduction
This article will demonstrate a deadlock program through Java code, and use the jstack
tools that come with JDK to verify whether a deadlock really occurs.
1. What is deadlock
Two or more threads hold the resources needed by each other, causing these threads to be in the "WAITING" state all the time.
2. Deadlock code demonstration
This example demonstrates the deadlock caused by two threads competing for each other's object locks.
public class DeadLock implements Runnable {
int condition;
static Object object1 = new Object();
static Object object2 = new Object();
public static void main(String[] args) {
DeadLock deadLock1 = new DeadLock();
DeadLock deadLock2 = new DeadLock();
deadLock1.condition = 1;
deadLock2.condition = 2;
Thread t1 = new Thread(deadLock1);
Thread t2 = new Thread(deadLock2);
t1.start();
t2.start();
}
@Override
public void run() {
System.out.println("当前是线程:" + condition);
if (condition == 1) {
synchronized (object1) {
System.out.println("线程1" + "得到object1锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1,卡在下一行代码");
synchronized (object2) {
System.out.println("打印出此行,表示线程1同时获得两把锁");
}
System.out.println("线程1执行完毕");
}
}
if (condition == 2) {
synchronized (object2) {
System.out.println("线程2" + "得到object2锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2,卡在下一行代码");
synchronized (object1) {
System.out.println("打印出此行,表示线程2同时获得两把锁");
}
System.out.println("线程2执行完毕");
}
}
}
}
operation result:
当前是线程:1
当前是线程:2
线程2得到object2锁
线程1得到object1锁
线程1,卡在下一行代码
线程2,卡在下一行代码
Analysis of running results:
- The lock held by thread 1
object1
, the lock held by thread 2object2
. - Then thread 1 competes for the
object2
lock; thread 2 competes for theobject1
lock. - Since thread 1 does not release the
object1
lock, and thread 2 does not releaseobject2
the lock, it will cause a deadlock.
3. Verify whether it is really deadlock
Enter in the command line: jps
, find out that the process number of our code program is6164
Then enter: on the command line to jstack -l 6164
analyze the program status:
A deadlock phenomenon was found in the program.
Summarize
After understanding the mechanism of deadlock, we can find a way to avoid deadlock. The first method is to pay attention to the order of locking. In the above code example, we only need to
keep the competition order of locks consistent in two threads ( For example, two threads compete for object1
locks first, and then compete for object2
locks), then deadlock will not occur. The second way to avoid deadlock is to
set a timeout, and if it exceeds a certain time, the lock is automatically released.
When the program is running, we can use the jstack
tool to check the running status of the program and whether there is a deadlock.