运行这个时,我得到IllegalMonitorStateException
,因为即使线程试图通知,当它没有锁定对象isEven
。这是为什么发生?如果线程锁定了对象,则线程应该只能进入synchronized块。为什么多个线程能够访问同步块?
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();
}
}
看来你正在做同样的功课为[这家伙(http://stackoverflow.com/q/33560337/4856258 )... –
注意:'synchronized'的用途不是为了防止两个线程同时执行相同的代码。其目的是防止两个线程同时访问相同的_data_。 –