死锁是在多线程编程中常常遇到的问题,现在用java编写一个简单的死锁程序。
程序在main()方法中启动2个线程,“线程-A”和“线程-B”。 线程-A 先拿到 lockA,再寻求拿到 lockB;线程-B 先拿到locB,再需求拿到lockA,如下图,于是变成循环等待,造成死锁。
代码
public class DeadLockDemo {
public static void main(String[] args) {
Object lockA = new Object();
Object lockB = new Object();
new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized (lockA) {
System.out.println(name + " got lockA, want LockB");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println(name + " got lockB");
System.out.println(name + ": say Hello!");
}
}
}
}, "线程-A").start();
new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized (lockB) {
System.out.println(name + " got lockB, want LockA");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockA) {
System.out.println(name + " got lockA");
System.out.println(name + ": say Hello!");
}
}
}
}, "线程-B").start();
}
}
运行结果:
线程-A got lockA, want LockB
线程-B got lockB, want LockA
程序死锁了,每个线程都不能完成。
转自:https://blog.csdn.net/xidianliuy/article/details/51568073