面试题 多线程交替打印abc
synchronized
package com.company;
public class SynchronizedPrint {
private final static Object lock = new Object();
static int flag = 1;
public static void main(String[] args) {
// write your code here
new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
//Synchronized while配合使用防止虚假唤醒
while (flag != 3) {
try {
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print('c');
flag = 1;
lock.notifyAll();
}
}
}, "c").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (flag != 2) {
try {
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print('b');
flag = 3;
lock.notifyAll();
}
}
}, "b").start();
new Thread(() -> {
for (int i = 0