运行此程序时,我得到了IllegalMonitorStateException
因为 Even 线程试图在它没有锁定对象时发出通知isEven
。为什么会这样?如果线程锁定了对象,则它应该只能进入同步块内部。
public class NumPrinter implements Runnable{
public static Boolean isEven = true;
private boolean isEvenThread;
private int i;
public void run() {
while(i < 100){
synchronized(isEven){
boolean notPrinting = (isEven ^ isEvenThread);
System.out.println(notPrinting);
if(notPrinting) {
try {
isEven.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(i + ",");
i = i+2;
isEven = !isEven;
isEven.notifyAll();
}
}
}
public NumPrinter(boolean isEvenThread) {
this.isEvenThread = isEvenThread;
if(isEvenThread)
i = 0;
else
i = 1;
}
}
public class MultiThreading {
public static void main(String[] args) {
Thread oddt = new Thread(new NumPrinter(false), "Odd");
Thread event = new Thread(new NumPrinter(true), "Even");
event.start();
oddt.start();
}
}