Java两个线程分别打印两个数组(多线程面试问题)

昨天面试面试官问了我一个多线程问题,说有两个数组,一个里面是ABCDEFG,另一个里面是1234567,现在用两个线程分别打印这两个数组,要求打印一个字母再打印一个数组,问我怎么实现。
我当时第一反应就是通过wait方法来实现,但是面试官说wait方法不行,notify会唤醒所有线程,所以有可能会继续执行当前线程,由于我对线程这块也不熟悉,当时没有发现哪里不对,今天写了个demo测试了下,发现是可以实现的,代码如下:

package com.example.demo.test;


public class ArrayPrinter {
    private static final Object lock = new Object(); // 用于线程同步的锁对象

    private static final char[] letters = {'A', 'B', 'C', 'D', 'F', 'F', 'G'};
    private static final int[] numbers = {1, 2, 3, 4, 5, 6, 7};

    private static volatile int index = 0; // 当前要打印的索引

    public static void main(String[] args) {
        Thread letterThread = new Thread(() -> {
            for (char letter : letters) {
                synchronized (lock) {
                    try {
                        while (index % 2 != 0) {
                            lock.wait(); // 如果不是字母的打印顺序,则等待
                        }
                        System.out.print(letter);
                        index++;
                        lock.notify(); // 唤醒数字线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread numberThread = new Thread(() -> {
            for (int number : numbers) {
                synchronized (lock) {
                    try {
                        while (index % 2 != 1) {
                            lock.wait(); // 如果不是数字的打印顺序,则等待
                        }
                        System.out.print(number);
                        index++;
                        lock.notify(); // 唤醒字母线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        letterThread.start();
        numberThread.start();
    }
}


执行结果:

A1B2C3D4F5F6G7
Process finished with exit code 0

最后,notify方法是唤醒等待线程中的一个线程,notifyall是唤醒全部等待线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子非衣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值