public class ThreadPrinterA1B2 {
private static class Print {
private boolean flag = true;
private int number = 0;
synchronized void printNumber() throws InterruptedException {
if (!flag) this.wait();
for (int i = 0; i < 2; i++) {
//要求是一次打印两个数字一个字母
System.out.println(++number);
}
flag = false;
notifyAll();
}
synchronized void printLetter(int i) throws InterruptedException {
if (flag) this.wait();
System.out.println((char) ('A' + i));
flag = true;
notifyAll();
}
}
public static void main(String[] args) {
Print print = new Print();
new Thread(() -> {
for (int i = 0; i < 26; i++) {
try {
print.printNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 26; i++) {
try {
print.printLetter(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
输出结果:
1
2
A
3
4
B
.....