Unlocking lock owned by another thread java

前端 未结 5 923
借酒劲吻你
借酒劲吻你 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:14

    I've done this with an AtomicReference which gets zero points for elegance, but I don't know of another way.

    class PseudoLock {
    
        private final AtomicReference mylock = new AtomicReference<>(Boolean.FALSE);
    
    
        boolean trylock() {
            return mylock.compareAndSet(Boolean.FALSE, Boolean.TRUE);
        }
    
        void unlock() {
            boolean done = mylock.compareAndSet(Boolean.TRUE, Boolean.FALSE);
            if (!done) {
                throw new IllegalStateException("Cannot unlock an unlocked thread");
            }
        }
    }
    

    ''''

提交回复
热议问题