You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用交替线程实现交替打印?附本人可用实现代码

嘿,你已经成功搞定了三个线程交替打印递增数字的需求,这代码逻辑很扎实!我把你的代码补全并整理成更易读的格式,再拆解下核心实现思路,方便大家参考:

需求说明

让三个线程按固定顺序交替打印数字:Thread 1打印1,Thread 2打印2,Thread 3打印3,Thread 1打印4,以此循环直到数字达到100。

完整可运行代码
class Display implements Runnable {
    int threadId;
    static int v = 1;
    static int turn = 1; // 初始轮到线程1执行
    static Object monitor = new Object(); // 共享锁对象

    Display(int id) {
        this.threadId = id;
    }

    public void run() {
        print();
    }

    private void print() {
        while (v < 100) {
            try {
                Thread.sleep(1000); // 延迟1秒,让交替效果更直观
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt(); // 重置中断状态
            }

            synchronized (monitor) {
                // 不是当前线程的轮次,等待
                while (turn != threadId) {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                }

                // 轮到当前线程,打印数字
                System.out.println("Thread " + threadId + " prints: " + v);
                v++;
                // 更新轮次:1→2→3→1循环
                turn = turn % 3 + 1;
                // 唤醒其他等待的线程
                monitor.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Display(1)).start();
        new Thread(new Display(2)).start();
        new Thread(new Display(3)).start();
    }
}
核心实现解析
  • 共享状态控制:用static修饰的v(当前打印数字)和turn(当前执行的线程ID),保证所有线程共享同一状态;monitor作为全局锁,确保线程间的同步操作。
  • 等待/唤醒机制:每个线程进入同步块后,先检查turn是否等于自己的ID,若不是则调用wait()释放锁并等待;当轮到自己时,打印数字、更新v和turn,再调用notifyAll()唤醒其他等待的线程。
  • 中断处理:捕获InterruptedException后,不仅打印异常信息,还重置线程的中断状态,避免后续逻辑出现异常。
  • 延迟效果:Thread.sleep(1000)是为了让交替打印的效果更直观,实际场景中可以根据需求调整或移除。

内容的提问来源于stack exchange,提问作者somerandomguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:24:42