2008-09-30 22 views

回答

11

一个try/finally块,你可以得到这种行为最接近的事:像迈克说,finally块应该是你的选择

Lock l = new Lock(); 
l.lock(); // Call the lock before calling try. 
try { 
    // Do some processing. 
    // All code must go in here including break, return etc. 
    return something; 
} finally { 
    l.unlock(); 
} 
+0

“l.lock()” 要真正之前被称为“试“根据示例:http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Lock.html – McDowell 2008-09-30 13:11:00

2

。看到finally block tutorial,其中指出:

的finally块总是执行时 try块退出。这确保 即使 发生意外的异常也会执行finally块。

0

一个更好的方式来做到这一点是使用try-与资源的语句,它可以让你模拟天生C++的RAII mechanism

public class MutexTests { 

    static class Autolock implements AutoCloseable { 
     Autolock(ReentrantLock lock) { 
      this.mLock = lock; 
      mLock.lock(); 
     } 

     @Override 
     public void close() { 
      mLock.unlock(); 
     } 

     private final ReentrantLock mLock; 
    } 

    public static void main(String[] args) throws InterruptedException { 
     final ReentrantLock lock = new ReentrantLock(); 

     try (Autolock alock = new Autolock(lock)) { 
      // Whatever you need to do while you own the lock 
     } 
     // Here, you have already released the lock, regardless of exceptions 

    } 

}