1
我想使用线程增加一行矩阵中的数字+1。当线程访问时,矩阵不能很好地打印
- 两个线程不能同时
- 两个纱线可以在同一时间
我写访问不同排在同一行访问的是(只有共享资源的方法):
public void increaseRow(Integer row) {
if (!mapForRow.containsKey(row))
mapForRow.put(row, "not increased");
if (mapForRow.get(row).equals("not increased")) {
lock.lock();
try {
while (rowIncreased) {
condition.await();
}
mapForRow.get(row).equals("increased");
rowIncreased = true;
for (int j = 0; j < matrix.length; j++)
setMatrix(row, j, matrix[row][j] + 1);
rowIncreased = false;
// replace the value
mapForRow.get(row).equals(" not increased");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println();
System.out.println("begin print matrix");
for (int i = 0; i < row; i++) {
System.out.println();
for (int j = 0; j < column; j++)
System.out.print(matrix[i][j]);
}
System.out.println();
System.out.println("end print matrix ");
System.out.println();
lock.unlock();
condition.notifyAll();
}
}
}
矩阵被初始化为10行10列,开始线程也是10
而是通过输出I” M得到这个:
begin print matrix
0000000000
0000000000
0000000000
0000000000
end print matrix
begin print matrix
00Exception in thread "Thread-0" 00000000
0000000000
0000000000
end print matrix
java.lang.IllegalMonitorStateException
[...]
我能理解抛出的异常,但为什么矩阵没有完全显示?
谢谢你的回答,我会试试看。但是,你能解释一下为什么线程中断他们的打印? – 2014-10-16 10:34:42
该异常似乎被未捕获的异常处理程序捕获,而不是由您的代码块中的异常处理程序捕获。因此,当你的finally锁被 – PeterK 2014-10-16 10:37:09
锁释放时,它不是nullPointException,而是IllegalMonitorStateException,如果你看到锁和解锁在try-catch-finally块中。 – 2014-10-16 11:35:04