2014-10-16 50 views
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 
[...] 

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

回答

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

谢谢你的回答,我会试试看。但是,你能解释一下为什么线程中断他们的打印? – 2014-10-16 10:34:42

+0

该异常似乎被未捕获的异常处理程序捕获,而不是由您的代码块中的异常处理程序捕获。因此,当你的finally锁被 – PeterK 2014-10-16 10:37:09

+0

锁释放时,它不是nullPointException,而是IllegalMonitorStateException,如果你看到锁和解锁在try-catch-finally块中。 – 2014-10-16 11:35:04