面试经典题:创建三个线程,按顺序依次循环打印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;}@Overridepublic 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();}
}