← 中文资源

简体中文版本

锁顺序避免死锁

转账双方以相反顺序拿两把锁就会死锁:各自持有一把再等对方。按账户 id 统一加锁顺序后,线程只会排队等待,方向相反的两笔转账都能顺利完成。

阅读英文原文

实现说明

锁顺序避免死锁的核心是类 TransferOrders、Account和函数 transfer。

使用要点

  • 演示输出是带标签的(moved、both finished, no deadlock:),每个操作都会留下自己的一行标注。
  • main 按顺序串起 transfer;运行文件就会把这个流程跑一遍。

常见问题

运行「锁顺序避免死锁」会打印什么?

整个文件跑完,输出行以 moved、both finished, no deadlock: 这类前缀开头。

主要签名是 static void transfer(Account from, Account to, int amount)

核心语句

Thread one = new Thread(() -> transfer(ALICE, BOB, 10));
Thread two = new Thread(() -> transfer(BOB, ALICE, 5));
+ (one.getState() != Thread.State.BLOCKED
&& two.getState() != Thread.State.BLOCKED));

代码示例

import java.util.concurrent.locks.ReentrantLock;

public class TransferOrders {

    record Account(long id, ReentrantLock lock) {}

    static final Account ALICE = new Account(1, new ReentrantLock());
    static final Account BOB = new Account(2, new ReentrantLock());

    // 死锁根源:两个线程以相反顺序拿两把锁,各自持有一把再等对方。
    // 修复:全系统约定一致的加锁顺序(这里按账户 id 升序),只能排队不能成环
    static void transfer(Account from, Account to, int amount) {
        ReentrantLock first = from.id() < to.id() ? from.lock() : to.lock();
        ReentrantLock second = first == from.lock() ? to.lock() : from.lock();
        first.lock();
        try {
            second.lock();
            try {
                System.out.println("moved " + amount + " from id " + from.id()
                        + " to id " + to.id());
            } finally {
                second.unlock();
            }
        } finally {
            first.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 方向相反的两笔转账:一致的顺序让它们排队而非互相等待
        Thread one = new Thread(() -> transfer(ALICE, BOB, 10));
        Thread two = new Thread(() -> transfer(BOB, ALICE, 5));
        one.start();
        two.start();
        one.join(2000);
        two.join(2000);
        System.out.println("both finished, no deadlock: "
                + (one.getState() != Thread.State.BLOCKED
                && two.getState() != Thread.State.BLOCKED));
    }
}