死锁DeadLock
死锁是指两个或两个以上的线程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。
public class Lock {
private static Object obj1 = new Object();
private static Object obj2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
try {
while (true) {
synchronized (obj1) {
System.out.println("lock obj1 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
synchronized (obj2) {
System.out.println("lock obj2 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
}
}
}
}
catch (Exception e) {
}
}
).start();
new Thread(() -> {
try {
while (true) {
synchronized (obj2) {
System.out.println("lock obj2 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
synchronized (obj1) {
System.out.println("lock obj1 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
}
}
}
}
catch (Exception e) {
}
}
).start();
}
}
模拟银行转账的Demo
下面我们来看一个关于银行转账的死锁例子。在银行转账问题中,我们需要对转出方和转入方两个账户加锁,以确保转账过程中金额的正确性。
我们在一般实现中,可能会采用以下手段,比如类似先锁转出账户,后锁转入账户的方式。实际在很多类似订单操作、库存操作中可能都会有类似逻辑。
/**
* 银行转账动作接口
*/
public interface ITransfer {
/**
*
* @param from 转出账户
* @param to 转入账户
* @param amount 转账金额
* @throws InterruptedException
*/
void transfer(UserAccount from, UserAccount to, int amount)
throws InterruptedException;
}
/**
* 不安全的转账动作
*/
public class TrasnferAccount implements ITransfer {
@Override
public void transfer(UserAccount from, UserAccount to, int amount)
throws InterruptedException {
s