package com.study.demo;
import java.util.concurrent.TimeUnit;
class HoldLock implements Runnable{
String lockA;
String lockB;
public HoldLock(String lockA,String lockB){
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA){
System.out.println(Thread.currentThread().getName()+"\t 自己持有"+lockA+"尝试获得"+lockB);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
System.out.println(Thread.currentThread().getName()+"\t 自己持有"+lockB+"尝试获得"+lockA);
}
}
}
}
/**
* 死锁是指两个或两个以上进程在执行过程中,
* 因争夺资源造成的一种互相等待的现象
* 若无外力干涉他们都无法推进下去
*/
public class DeadLockDemo {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new HoldLock(lockA,lockB)).start();
new Thread(new HoldLock(lockB,lockA)).start();
}
}