java - 当线程访问时,矩阵打印得不好

标签 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
[...]

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

最佳答案

为什么不使用 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/

相关文章:

java - 使用loci.plugins(生物格式)时出现SLF4J version_mismatch错误

java - 如何在 Java 中将帧速率限制在 60 fps?

python - Astroscrappy 无法在多处理 Jupyter 上工作

javascript - 在javascript中创建 "m x n"二维数组

matlab - 根据 "surface"值提取 3D 矩阵的列 - 矢量化

Java if语句数据输入限制

java - 降序排序算法

c++ - 从另一个 std::thread 调用 Qt 对象方法

c++ - 为什么 pthread_mutex_t 在尝试通过来自两个不同进程的共享内存进行锁定时会出现段错误?

python - 在python中对矩阵的值进行排序