1这段循环按顺序打印 ABCD...的多线程程序的输出结果为什么不对?
2我中文注释中的理解是否正确?
import java.util.HashMap;
public class Main{
static char globalFlag = 'A';
static HashMap m = new HashMap<>();
static class MyThread extends Thread{
char flag;
MyThread(char flag){
this.flag = flag;
}
@Override
public void run() {
while (true){
Object thisLock = m.get(flag);
char nextFlag = (char)('A' + (flag + 1) % 26);
Object nextObjectLock
synchronized (thisLock){
if (flag != globalFlag){
try {
thisLock.wait(); // 线程会被阻塞住,直到其他线程执行对应Lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(flag);
globalFlag = nextFlag;
}
// 唤醒下一个线程
Object nextObjectLock = m.get(nextFlag);
synchronized(nextObjectLock){
nextObjectLock.notify(); // 通知执行nextObjectLock.wait()的线程可以继续执行
}
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 26; i++) {
m.put((char)('A' + i),new Object());
}
for (int i = 0; i < 26; i++) {
new MyThread((char)('A' + i)).start();
}
}
}