我想使用线程将矩阵行内的数字增加 +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
但是通过输出我得到了这个:
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
[...]
我可以理解抛出的异常,但是为什么矩阵没有完全显示?
最佳答案
为什么不使用 AtomicInteger
来实现这一点。这些可以从多个线程安全地访问和操作,而不需要锁定。
如果您将代码想象为位于以 //
开头的行之间,您可以看到,当锁定到位时,NullPointerException
将被捕获并处理,但是如果抛出任何其他异常(未在该 block 中捕获的异常),则该异常将在堆栈跟踪中向上移动,直到被捕获,并且当它被捕获时,您的锁将早已被释放。
try {
// start of your code
lock.lock();
try {
doStuff();
} catch(InterruptedException e) {
System.out.println("in lock");
} finally {
lock.unlock();
}
// end of your code
} catch(Exception e) { // IllegalMonitorStateException caught here
System.out.println("not in lock");
}
关于java - 当线程访问时,矩阵打印得不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26402121/