Gemini永久会员 三个线程(A、B、C)交替执行

要实现三个线程(A、B、C)交替执行(即按顺序A→B→C→A→B→C...循环),可以通过线程同步机制(如wait()/notify()ReentrantLock+Condition)或使用Semaphore信号量来控制。以下是两种常见实现方式:


方法1:使用 wait()notify()

通过共享锁和条件变量实现线程交替执行:

java 复制代码
public class AlternateThreads {
    private static final Object lock = new Object();
    private static int state = 0; // 0:A, 1:B, 2:C

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (state % 3 != 0) { // 检查是否是A的轮次
                        try { lock.wait(); } catch (InterruptedException e) {}
                    }
                    System.out.print("A");
                    state++;
                    lock.notifyAll(); // 唤醒其他线程
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (state % 3 != 1) { // 检查是否是B的轮次
                        try { lock.wait(); } catch (InterruptedException e) {}
                    }
                    System.out.print("B");
                    state++;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (state % 3 != 2) { // 检查是否是C的轮次
                        try { lock.wait(); } catch (InterruptedException e) {}
                    }
                    System.out.print("C");
                    state++;
                    lock.notifyAll();
                }
            }
        }).start();
    }
}

输出示例ABCABCABC...

关键点

  1. 共享变量 state 记录当前轮次。
  2. 每个线程通过 wait() 等待自己的轮次,执行后通过 notifyAll() 唤醒其他线程。
  3. synchronized 确保线程安全。

方法2:使用 ReentrantLock + Condition(更灵活)

通过显式锁和条件变量实现更清晰的交替控制:

java 复制代码
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class AlternateThreadsWithLock {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();
    private static int state = 0; // 0:A, 1:B, 2:C

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                lock.lock();
                try {
                    while (state % 3 != 0) {
                        conditionA.await();
                    }
                    System.out.print("A");
                    state++;
                    conditionB.signal(); // 唤醒B
                } catch (InterruptedException e) {}
                finally { lock.unlock(); }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                lock.lock();
                try {
                    while (state % 3 != 1) {
                        conditionB.await();
                    }
                    System.out.print("B");
                    state++;
                    conditionC.signal(); // 唤醒C
                } catch (InterruptedException e) {}
                finally { lock.unlock(); }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                lock.lock();
                try {
                    while (state % 3 != 2) {
                        conditionC.await();
                    }
                    System.out.print("C");
                    state++;
                    conditionA.signal(); // 唤醒A
                } catch (InterruptedException e) {}
                finally { lock.unlock(); }
            }
        }).start();
    }
}

优势

  • 每个线程有独立的 Condition,避免不必要的唤醒(比 notifyAll() 更高效)。
  • 代码结构更清晰,易于扩展。

方法3:使用 Semaphore 信号量

通过信号量控制线程的执行顺序:

java 复制代码
import java.util.concurrent.Semaphore;

public class AlternateThreadsWithSemaphore {
    private static Semaphore semaphoreA = new Semaphore(1);
    private static Semaphore semaphoreB = new Semaphore(0);
    private static Semaphore semaphoreC = new Semaphore(0);

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                try {
                    semaphoreA.acquire();
                    System.out.print("A");
                    semaphoreB.release();
                } catch (InterruptedException e) {}
            }
        }).start();

        new Thread(() -> {
            while (true) {
                try {
                    semaphoreB.acquire();
                    System.out.print("B");
                    semaphoreC.release();
                } catch (InterruptedException e) {}
            }
        }).start();

        new Thread(() -> {
            while (true) {
                try {
                    semaphoreC.acquire();
                    System.out.print("C");
                    semaphoreA.release();
                } catch (InterruptedException e) {}
            }
        }).start();
    }
}

原理

  • 初始时 semaphoreA 有一个许可,其他信号量为0。
  • 每个线程执行后释放下一个线程的信号量,形成循环。

总结

  • 简单场景 :用 wait()/notify()Semaphore
  • 复杂场景 :用 ReentrantLock + Condition(更灵活高效)。
  • 关键点:确保线程按顺序释放资源,避免死锁或竞争条件。

根据需求选择合适的方法即可!

相关推荐
正宗咸豆花1 分钟前
端到端AI决策架构如何重塑实时协作体验?
人工智能·架构
gyx_这个杀手不太冷静14 分钟前
OpenCode 深度解析:架构设计、工具链集成与工程化实践
前端·架构·ai编程
luffy545914 分钟前
Rust语言入门-变量篇
开发语言·后端·rust
liangshanbo121519 分钟前
大模型 RAG 向量数据工程全链路架构笔记
笔记·架构
MegaDataFlowers44 分钟前
快速上手Spring
java·后端·spring
小江的记录本44 分钟前
【MyBatis-Plus】Spring Boot + MyBatis-Plus 进行各种数据库操作(附完整 CRUD 项目代码示例)
java·前端·数据库·spring boot·后端·sql·mybatis
左左右右左右摇晃1 小时前
Java 笔记--OOM产生原因以及解决方法
java·笔记
大傻^1 小时前
Spring AI Alibaba Function Calling:外部工具集成与业务函数注册
java·人工智能·后端·spring·springai·springaialibaba
逆境不可逃1 小时前
LeetCode 热题 100 之 33. 搜索旋转排序数组 153. 寻找旋转排序数组中的最小值 4. 寻找两个正序数组的中位数
java·开发语言·数据结构·算法·leetcode·职场和发展
掘根1 小时前
【微服务即时通讯】环境搭建10——Curl实现邮件通知服务
微服务·云原生·架构