System.out.println("Thread state: " + threads[i].getState());
threads[i].notify();
產生以下輸出:Java - 無法通知等待線程?
Thread state: WAITING
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at MyPakc.An.run(An.java:49)
at java.lang.Thread.run(Thread.java:679)
這是怎麼回事?爲什麼我不能通知睡眠線程?
編輯:
package Part2;
import java.util.List;
import javax.swing.JPanel;
class BThread extends Thread{
private boolean completedThisIter = false;
@Override
public synchronized void run() {
while (true) {
completedThisIter = false;
doStuff()
System.out.println("Completed iter");
completedThisIter = true;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean getCompletedThisIter() {
return completedThisIter;
}
}
編輯:對於線程[]類的代碼下面是調用此
public synchronized void run(){
// OTHER STUFF
for (int iter = 0; iter < 1212; ++iter){
System.out.println("Iter " + iter);
lastAssignedBallIndex = -1;
for (int i = 0; i < numThreads; i++) {
//System.out.println("Num " + numThreads + " " + i);
//ballThreads[i] = new BallThread(ballList.subList(lastAssignedBallIndex+1,lastAssignedBallIndex+numBallsPerThread),
// ballPanel);
//lastAssignedBallIndex += numBallsPerThread;
System.out.println("State " + ballThreads[i].getState());
if (ballThreads[i].getState() == Thread.State.NEW) {
ballThreads[i].start();
} else { //if (ballThreads[i].getState() == Thread.State.BLOCKED) {
System.out.println("Thread state: " + ballThreads[i].getState());
ballThreads[i].notify();
}
}
//try{
for (int i = 0; i < numThreads; i++) {
while (!ballThreads[i].getCompletedThisIter()) {
System.out.println("iter:" + iter + " ball:" + i + " " + ballThreads[i].getCompletedThisIter());
//wait(); // TODO elliminate polling here
}
}
System.out.println("Joined");
//}
// catch(InterruptedException ie){ie.printStackTrace();}
ballPanel.repaint();
notifyAll();
try{
Thread.sleep(2);
}
catch (InterruptedException ie){}
}
}
你可以顯示正在等待的線程的代碼嗎? – 2012-07-21 04:48:50
你想達到什麼目的?通知'Thread'對象不會導致任何事情發生,除非有另一個線程調用'wait()'。 – SimonC 2012-07-21 04:57:40
是的,我給你的狀態輸出在調用notify()之前,你看到它正在等待 – Trup 2012-07-21 05:01:29