在线程访问时,矩阵打印效果不佳

时间:2014-10-16 10:30:02

标签: java multithreading matrix

我想使用线程将一行矩阵内的数字增加+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
[...]

我可以理解抛出的异常,但为什么矩阵没有完全显示?

1 个答案:

答案 0 :(得分:2)

为什么不使用AtomicInteger。这些可以从多个线程安全地访问和操作,而无需锁定。

如果您将代码想象在以//开头的行之间,您可以看到,NullPointerException将在锁定到位时被捕获并处理,但是如果有任何其他异常则抛出,一个未被捕获的块,异常将向上移动堆栈跟踪直到被捕获,并且当它被捕获时,锁定将很长时间被释放。

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");
}