题目难点:
- 如何控制线程间的通讯问题
- 如何控制在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();
}
}
}
}