Unlocking lock owned by another thread java

前端 未结 5 924
借酒劲吻你
借酒劲吻你 2020-12-30 01:40

I have a LockManager that manages the locks of several threads. Sometimes the threads are bad boys, and I have to kill them and ask the LockManager to release all their lock

5条回答
  •  醉梦人生
    2020-12-30 02:21

    Why don't you simply wrap the code of your thread around the following:

    ReentrantLock lock = ... obtain your lock somehow ...
    lock.lock();
    try {
      ... the "bad boy" code here ...
    } finally {
      lock.unlock();
    }
    

    Then, when your thread finishes (either by normally finishing, or by throwing an exception from your "kill"), it will release the lock.

    This is actually the way Oracle recommends using ReentrantLock: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

提交回复
热议问题