题目难点:
- 如何控制线程间的通讯问题
- 如何控制在100次以内
- 状态判断打印
//解决方案一:
public class TestDemo {
//总计数
private static final Integer COUNT = 100;
//当前计数
private static Integer count = 0;
//锁
private static Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
synchronized (lock) {
if (count + 1 <= COUNT) {
System.out.println("A");
count++;
//唤醒其他线程
lock.notifyAll();
try {
//当前线程等待
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(() -> {
while (true) {
synchronized (lock) {
if (count + 1 <= COUNT) {
System.out.println("B");
count++;
//唤醒其他线程
lock.notifyAll();
try {
//当前线程等待
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Java面试:三线程循环打印ABC的解决方案

本文探讨了在Java面试中常见的线程题目,重点在于解决线程间通讯,确保线程安全地循环打印'A'、'B'、'C'共100次,并控制在限定次数内完成。内容涉及线程状态判断和同步控制等关键点。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



