public class AlternatePrinting {
private static final Object lock = new Object();
//private static int count = 0;
private static boolean isThreadATurn = true;
public static void main(String[] args) {
Thread threadA = new Thread(() -> {
for (int i = 0; i < 5; i++) {
synchronized (lock) {
while (!isThreadATurn) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print("A");
//System.out.println("Thread A: " + "A");
//count++;
isThreadATurn = false;
lock.notifyAll();
}
}
});
Thread threadB = new Thread(() -> {
for (int i = 0; i < 5; i++) {
synchronized (lock) {
while (isThreadATurn) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print("B");
//count++;
isThreadATurn = true;
lock.notifyAll();
}
}
});
threadA.start();
threadB.start();
}
}
输出ABABABABAB