如何在Java中使用等待和通知而不使用IllegalMonitorStateException?
我有两个矩阵,我需要把它们相乘,然后打印每个细胞的结果。一旦一个单元格准备就绪,我就需要打印它,但例如,我需要在单元格[2][0]之前打印[0]单元格,即使[2][0]的结果先准备好。所以我需要按顺序打印。所以我的想法是让打印机线程等到multiplyThread通知它,正确的单元格已准备好打印,然后printerThread将打印出手机,然后返回等待等等。
所以我有一条线来做乘法:public void run() {
int countNumOfActions = 0; // How many multiplications have we done
int maxActions = randomize(); // Maximum number of actions allowed
for (int i = 0; i
{
result[rowNum][colNum] = result[rowNum][colNum] + row[i] * col[i];
countNumOfActions++;
// Reached the number of allowed actions
if (countNumOfActions >= maxActions)
{
countNumOfActions = 0;
maxActions = randomize();
yield();
}
}
isFinished[rowNum][colNum] = true;
notify();}
打印每个单元格的结果的线程:public void run(){
int j = 0; // Columns counter
int i = 0; // Rows counter
System.out.println("The result matrix of the multiplication is:");
while (i
{
synchronized (this)
{
try
{
this.wait();
}
catch (InterruptedException e1)
{
}
}
if (creator.getmThreads()[i][j].getIsFinished()[i][j] == true)
{
if (j
{
System.out.print(creator.getResult()[i][j] + " ");
j++;
}
else
{
System.out.println();
j = 0;
i++;
System.out.print(creator.getResult()[i][j] + " ");
}
}
}
现在它抛出了这些例外:Exception in thread "Thread-9" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)Exception in thread "Thread-6" Exception in thread "Thread-4"
java.lang.IllegalMonitorStateException
如果有人能帮助这段代码工作,我会非常感激的。