我一直在尋找一些關於多線程和通信的同步的教程,通過wait()和notifyAll()來解決這個問題,但他們沒有幫助我。據說,我的程序啓動了50個線程,檢查數組中的可用位置,如果沒有的話,進入等待模式。當它們結束時,notifyAll()恢復它們,以便它們可以查找空閒位置。但是,這導致了IllegalMonitorStateException的各種實例。Java - wait()和notifyAll()
@Override
public void run() {
try {
Random rnd = new Random(new Date().getTime());
boolean entrado = false;
int i = 0;
sm.acquire();
synchronized (biblioteca) {
System.out.println("Usuario " + id + " entra");
while (!entrado) {
for (i = 0; i < biblioteca.ordenadores.length && !entrado; i++) {
if (biblioteca.ordenadores[i] == 0) {
entrado = true;
break;
}
}
if (!entrado) {
System.out.println("Usuario " + id + " en la sala de espera");
wait();
}
}
biblioteca.ordenadores[i] = id;
System.out.println("Usuario " + id + " ocupa Ordenador " + i
+ "\nOrdenadores: " + biblioteca.muestraOrdenadores());
}
Thread.sleep(rnd.nextInt(2000));
synchronized (biblioteca) {
System.out.println("Usuario " + id + " termina de usar el Ordenador " + i + " y sale");
biblioteca.ordenadores[i] = 0;
notifyAll();
}
sm.release();
} catch (InterruptedException e) {
}
}
什麼是「sm」?哪一行拋出'IllegalMonitorStateException'? – 2014-11-25 14:20:33