这个考查线程同步和线程调度
public class Demo {
private static Object lock = new Object();
private static boolean printNumber = true;
public static void main(String[] args) {
Demo demo = new Demo();
Thread thread1 = new Thread(() -> demo.printNumbers());
Thread thread2 = new Thread(() -> demo.printLetters());
thread1.start();
thread2.start();
}
public void printNumbers() {
synchronized (lock) {
for (int i = 1; i <= 52; i += 2) {
try {
while (!printNumber) {
lock.wait();
}
System.out.println(i);
System.out.println(i + 1);
printNumber = false;
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void printLetters() {
synchronized (lock) {
for (char i = 'A'; i <= 'Z'; i++) {
try {
while (printNumber) {
lock.wait();
}
System.out.println(i);
printNumber = true;
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
【运行结果】