我想學習多線程和練習,我試圖打印奇數&偶數使用兩個線程。我創建了一個對象,它將充當這兩個線程的鎖。當我嘗試執行它時拋出java.lang.IllegalMonitorStateException
。使用多線程打印奇數和偶數
class EVENODDimpl implements Runnable {
int num;
int temp = 0;
Object lock = new Object();
public EVENODDimpl(int num) {
this.num = num;
}
public void run() {
try {
synchronized (lock) {
while(temp<num) {
temp++;
System.out.println(Thread.currentThread().getName()+" "+temp);
this.notify();
this.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主要方法:
public class EVENODD {
public static void main(String[] args) {
int i = 10;
EVENODDimpl ei = new EVENODDimpl(i);
Thread t1 = new Thread(ei,"EvenThread");
Thread t2 = new Thread(ei,"OddThread");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我認爲問題是,你正在同步一個對象,但然後調用另一個「通知」和「等待」。 – Tavo