3个线程交替打印ABC

package com.interview;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class ABC {
    private static final int COUNT = 20 * 3;//20是每个字母输出20遍
    private static int state = 1;          // 3是有3个字母交替输出,COUNT是总共输出的遍数
    public static void main(String[] args) {
        final Lock l = new ReentrantLock(true);

        Thread A = new Thread(new Runnable(){
            @Override
            public void run() {
                while (state <= COUNT) {
                    l.lock();
                    if(state <= COUNT && state%3==1){
                        System.out.println(Thread.currentThread().getName() + "线程->" + state + "A");
                        state ++;
                    }
                    l.unlock();
                }
            }
        },"A");
        Thread B = new Thread(new Runnable(){
            @Override
            public void run() {
                while (state <= COUNT) {
                    l.lock();
                    if(state <= COUNT && state%3==2){
                        System.out.println(Thread.currentThread().getName() + "线程->" + state + "B");
                        state ++;
                    }
                    l.unlock();
                }
            }
        },"B");
        Thread C = new Thread(new Runnable(){
            @Override
            public void run() {
                while (state <= COUNT) {
                    l.lock();
                    if(state <= COUNT && state%3==0){
                        System.out.println(Thread.currentThread().getName() + "线程->" + state + "C");
                        state++;
                    }
                    l.unlock();
                }
            }
        },"C");
        A.start();
        B.start();
        C.start();
    }
}


说明: 主线程是依次启动的ABC,那肯定是A最先获得锁,其次是B,是C。A获得到了锁后,打印了A,这时候锁被释放了,B会拿到锁的,这时候A是加在了AQS双向链表的尾部的,也就是C的后面,这里为了保证打印的顺序采取的是公平锁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用多线程编程来实现三个线程交替打印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',每个字母连续打印十次。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值