1.什么是死锁?
死锁是指两个或两个以上的线程在执行的过程中,由于争抢资源而出现互相等待的现象,若无外力的干涉它们将会无法推进下去。用我们通俗易懂的话讲,死锁就是吃着碗里的想着锅里的,但是又紧紧抓住自己已经已有的,死死不肯放手。
2.死锁的编码实现
class HoldThread implements Runnable{
private String lockA;
private String lockB;
public HoldThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA) {
System.out.println(Thread.currentThread().getName() + "持有锁:" + lockA + "还想要得到锁:" + lockB);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println(Thread.currentThread().getName() + "持有锁:" + lockB + "还想要得到锁:" + lockA);
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new HoldThread(lockA, lockB), "ThreadAAA").start();
new Thread(new HoldThread(lockB, lockA), "ThreadBBB").start();
}
}