我一直在寻找一些关于多线程和通信的同步的教程,通过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