Java实现两个线程交替打印一个字符串

Java实现两个线程交替打印一个字符串

面试时经常会遇到这类问题,可以用一些小例子来熟悉多线程的使用以及Object的wait和notify等相关知识。

回到这题:

  1. 首先我们需要一个字符串,可以拆分成数组或者List
  2. 其次我们需要一把锁,用于控制字符串的有序打印
  3. 最后我们还需要一个指针,用于线程间通信(通知打印到哪里了)

代码如下:
线程a打印字符串方法:

public static void printStringA(String[] strs) throws InterruptedException {
        while (strs.length > index) {
            synchronized (LOCK) {
                if (index % 2 == 0) {
                    log.info(Thread.currentThread().getName() + ": " +strs[index]);
                    index++;
                    // notify 随机唤醒一个持有该锁的其他线程
                    LOCK.notify();
                } else {
                    // 阻塞当前线程
                    LOCK.wait();
                }
            }
        }
    }

线程b打印字符串方法:

public static void printStringB(String[] strs) throws InterruptedException {
        while (strs.length > index) {
            synchronized (LOCK) {
                if (index % 2 == 1) {
                    log.info(Thread.currentThread().getName() + ": " +strs[index]);
                    index++;
                    LOCK.notify();
                } else {
                    LOCK.wait();
                }
            }
        }
    }

mian方法测试:

	/**
     * 打印字符串的锁
     */
    private static final Object LOCK = new Object();
    /**
     * 控制打印位置的指针
     */
    private static volatile int index = 0;
    /**
     * 打印的线程池
     */
    static ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        var str = "我是个大帅逼";
        var strs = str.split("");
        executor.execute(() -> {
            try {
                printStringA(strs);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executor.execute(() -> {
            try {
                printStringB(strs);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executor.shutdown();
    }

测试效果如下:
在这里插入图片描述

为了实现这个需求,我们可以使用Java中的`Thread`类以及`synchronized`关键字来控制线程的执行顺序。以下是一个简单的示例: ```java public class Print交替 { private int turn = 0; // 用于跟踪哪个线程打印 public static void main(String[] args) { Print交替 printer = new Print交替(); Thread thread1 = new Thread(printer::printString1); Thread thread2 = new Thread(printer::printString2); thread1.start(); // 启动第一个线程 thread2.start(); // 启动第二个线程 } public synchronized void printString1() { while (true) { if (turn == 1) { // 当轮到我们打印时 System.out.println(Thread.currentThread().getName() + ": Hello"); turn = 2; // 下一个回合轮到另一个线程 break; } try { wait(); // 等待当前线程被唤醒 } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void printString2() { while (true) { if (turn == 2) { // 当轮到我们打印时 System.out.println(Thread.currentThread().getName() + ": World"); turn = 1; // 下一个回合轮到另一个线程 break; } try { wait(); // 等待当前线程被唤醒 } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 在这个例子中,`printString1` 和 `printString2` 都是同步方法,它们之间共享了`turn`变量来决定谁先打印。当某个线程进入循环后,如果它的回合(turn)不是1,那么它会调用`wait()`让自己挂起并释放锁。此时,另一个线程可以获取锁并执行其相应的方法,然后改变`turn`的值并调用`notifyAll()`通知所有等待该锁的线程。这样,两个线程就可以交替打印"Hello"和"World"了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值