Skip to content
java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class TaskCoordinator {
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    // 线程 A 的任务
    public void taskA() {
        lock.lock();
        try {
            System.out.println("Thread A: 正在执行任务 A...");
            // 模拟任务执行
            Thread.sleep(2000);
            System.out.println("Thread A: 任务 A 完成");
            condition.signal();  // 唤醒线程 B
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }

    // 线程 B 的任务
    public void taskB() throws InterruptedException {
        lock.lock();
        try {
            System.out.println("Thread B: 等待任务 A 完成...");
            condition.await();  // 等待线程 A 完成
            System.out.println("Thread B: 任务 A 完成,开始执行任务 B");
        } finally {
            lock.unlock();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        TaskCoordinator coordinator = new TaskCoordinator();

        // 线程 A
        new Thread(coordinator::taskA).start();

        // 线程 B
        new Thread(() -> {
            try {
                coordinator.taskB();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}