面试经典题:创建三个线程,按顺序依次循环打印hello+i

二面被问到的手撕题,自己总计一下。考察的还是比较基础的,但也是对自己知识领悟程度的考察。
写一个程序,要求创建三个线程依次打印hello+线程号。
考察多线程和同步的知识点应用
这里设置为打印10轮。

package 多线程;

/**
 * @Author wuyifan
 * @Date 2024/6/4 20:11
 * @Version 1.0
 */
class PrintSequence implements Runnable {
    private int threadId;
    private static final Object lock = new Object();
    private static int currentThreadId = 0;
    private int printCount = 10;

    public PrintSequence(int threadId) {
        this.threadId = threadId;
    }

    @Override
    public void run() {
        for (int i = 0; i < printCount; ) {
            synchronized (lock) {
                if (currentThreadId % 3 == threadId) {
                    System.out.println("Thread " + threadId + ": hello" + (i + 1));
                    i++;
                    currentThreadId++;
                    lock.notifyAll(); // 唤醒所有等待的线程
                } else {
                    try {
                        lock.wait(); // 等待其他线程的唤醒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

public class New3Thread {
    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintSequence(0), "T1");
        Thread t2 = new Thread(new PrintSequence(1), "T2");
        Thread t3 = new Thread(new PrintSequence(2), "T3");

        t1.start();
        t2.start();
        t3.start();
    }
}

相关推荐

  1. 线顺序循环执行

    2024-06-05 21:30:02       36 阅读
  2. 手撕面试:多线交叉打印ABC

    2024-06-05 21:30:02       21 阅读
  3. C++ 多线顺序打印

    2024-06-05 21:30:02       36 阅读
  4. 线面试

    2024-06-05 21:30:02       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-05 21:30:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-05 21:30:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-05 21:30:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-05 21:30:02       20 阅读

热门阅读

  1. 【FPGA约束】如何对fpga进行io约束

    2024-06-05 21:30:02       9 阅读
  2. spring-Bean的作用域

    2024-06-05 21:30:02       8 阅读
  3. Flutter 中的 Table 小部件:全面指南

    2024-06-05 21:30:02       7 阅读