给你三个线程,如何让它们交替打印1、2、3

3 篇文章 0 订阅

问题提出

前几天写了一篇 Java多线程:写一下两个线程交替打印 0~100 的奇偶数 介绍了如果用 wait/notify 控制两个线程交替执行,最后留了一个扩展问题:有三个线程,要求让它们交替输出 1、2、3,打印内容如下:

线程1:1
线程2:2
线程3:3
线程1:1
线程2:2
线程3:3
……

该如何实现?

分析

沿用两个线程的交替打印的思路,重点是当第一个线程获取到锁的时候第二个线程在wait状态等待被唤醒,此时第一个线程完成任务时,主动唤醒第二个线程,自己进入等待状态,不与之竞争。这样就能起到“我做完轮到你,你做完轮到我”的状态。

而三个线程的情况下是无法简单通过一个锁来完成的,因为当多个线程在等待时,我们无法通过 notify 来唤醒指定的线程。如何解决呢?

解决

我们可以使用三个锁 lock1、lock2 和 lock3,分别对应要执行的三个线程 t1、t2 和 t3。

当前线程t1执行时,先锁定下一个线程t2对应的锁 lock2,然后再获取自己线程对应的锁 lock1,当两个锁都拿到时才打印,并唤醒在等待 lock1 的线程t3,退出 lock1 的同步代码块,释放 lock1,此时 t3 拿到 lock1,等待获取 lock3(lock3 在启动时就被 t2 占了)。之后释放 lock2 让 t2 进入执行状态自己进入等待 lock2 被唤醒,此时线程进行等待状态,以免进入下一次循环与 t2 竞争 lock2。

t2 也是相同的逻辑,唤醒等待 lock2 的 t1,此时 t1 才从上次循环中退出再次获取 lock2,然后释放 lock3, 让 t3 进入执行状态。

最终的目的就是要实现三个线程相互等待前面两个线程执行完,形成一个循环。

private int count = 0;
private final Object lock1 = new Object();
private final Object lock2 = new Object();
private final Object lock3 = new Object();

public static void main(String[] args) throws InterruptedException {
    new MultiTurningThread().multiTurning();
}

public void multiTurning() throws InterruptedException {
    Thread t1 = new Thread(() -> {
        while (count <= 100) {
            synchronized (lock2) {
                synchronized (lock1) {
                    System.out.println("线程1: 1");
                    count++;
                    // 唤醒正等待 lock1 的 t3
                    lock1.notifyAll();
                }
                try {
                    // 如果还需要继续执行,则让出 lock2 让 t2 执行,自己进入等待状态
                    if (count <= 100) {
                        lock2.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    Thread t2 = new Thread(() -> {
        while (count <= 100) {
            synchronized (lock3) {
                synchronized (lock2) {
                    System.out.println("线程2: 2");
                    count++;
                    // 唤醒正在等待 lock2 的 t1
                    lock2.notifyAll();
                }
                try {
                    // 如果还需要继续执行,则让出 lock3 让 t3 执行,自己进入等待状态
                    if (count <= 100) {
                        lock3.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    Thread t3 = new Thread(() -> {
        while (count <= 100) {
            synchronized (lock1) {
                synchronized (lock3) {
                    System.out.println("线程3: 3");
                    count++;
                    // 唤醒正在等待 lock3 的 t2
                    lock3.notifyAll();
                }
                try {
                    // 如果还需要继续执行,则让出 lock1 让 t1 执行,自己进入等待状态
                    if (count <= 100) {
                        lock1.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    t1.start();
    t2.start();
    t3.start();
}

三个线程的执行逻辑都是一样的,因此可以抽取成实现 Runnable 的对象:

 private int count = 0;
private final Object lock1 = new Object();
private final Object lock2 = new Object();
private final Object lock3 = new Object();

public static void main(String[] args) throws InterruptedException {
    new MultiTurningThread().multiTurning();
}

public void multiTurning() throws InterruptedException {
    Thread t1 = new Thread(new MultiTurningRunner(lock2, lock1, "线程1: 1"));
    Thread t2 = new Thread(new MultiTurningRunner(lock3, lock2, "线程2: 2"));
    Thread t3 = new Thread(new MultiTurningRunner(lock1, lock3, "线程3: 3"));
    t1.start();
    t2.start();
    t3.start();
}

class MultiTurningRunner implements Runnable {
    private final Object nextLock;
    private final Object currentLock;
    private final String content;

    public MultiTurningRunner(Object nextLock, Object currentLock, String content) {
        this.nextLock = nextLock;
        this.currentLock = currentLock;
        this.content = content;
    }

    @Override
    public void run() {
        while (count <= 100) {
            synchronized (nextLock) {
                synchronized (currentLock) {
                    System.out.println(content);
                    count++;
                    // 唤醒等待当前锁的线程
                    currentLock.notifyAll();
                }
                try {
                    // 如果还需要继续执行,则让出下一个线程对应的锁并进入等待状态
                    if (count <= 100) {
                        nextLock.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

执行结果:

线程1: 1
线程2: 2
线程3: 3
线程1: 1
线程2: 2
线程3: 3
……

参考文章:

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
你可以使用多线程编程来实现三个线程交替打印abc。下面是一个示例代码: ```python import threading class PrintABC: def __init__(self): self.current_letter = 'A' self.lock = threading.Lock() def print_a(self): for _ in range(10): with self.lock: while self.current_letter != 'A': self.lock.wait() print('A', end='') self.current_letter = 'B' self.lock.notify_all() def print_b(self): for _ in range(10): with self.lock: while self.current_letter != 'B': self.lock.wait() print('B', end='') self.current_letter = 'C' self.lock.notify_all() def print_c(self): for _ in range(10): with self.lock: while self.current_letter != 'C': self.lock.wait() print('C', end='') self.current_letter = 'A' self.lock.notify_all() def main(): printer = PrintABC() thread_a = threading.Thread(target=printer.print_a) thread_b = threading.Thread(target=printer.print_b) thread_c = threading.Thread(target=printer.print_c) thread_a.start() thread_b.start() thread_c.start() thread_a.join() thread_b.join() thread_c.join() if __name__ == '__main__': main() ``` 这个例子中,我们创建了一个 `PrintABC` 类,其中包含了三个方法 `print_a`、`print_b` 和 `print_c` 分别用于打印字母 'A'、'B' 和 'C'。在每个方法中,使用 `with self.lock` 来获取锁对象并进入临界区域。通过 `self.current_letter` 来确定当前应该打印的字母,并使用 `while self.current_letter != 'A'` 等待其他线程改变 `self.current_letter` 的值。当当前字母符合要求时,打印字母并切换到下一个字母,然后使用 `self.lock.notify_all()` 唤醒其他等待的线程。 在 `main` 方法中,我们创建了三个线程并分别启动它们,然后使用 `join` 方法等待所有线程执行完毕。运行这段代码时,你将会看到三个线程交替打印字母 'A'、'B' 和 'C',每个字母连续打印十次。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值