java释放锁_java – 一个线程在完成后释放锁吗?
簡(jiǎn)單測(cè)試可能會(huì)顯示在線程終止時(shí)未釋放鎖定:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public static void main(String[] args) {
final Lock l = new ReentrantLock();
Thread t = new Thread() {
@Override
public void run() {
System.out.println(Thread.currentThread()+": Acquire lock");
l.lock();
System.out.println(Thread.currentThread()+": Lock aquired: wait");
LockSupport.parkNanos(1_000_000_000);
System.out.println(Thread.currentThread()+"; Exiting");
}
};
t.start();
LockSupport.parkNanos(500_000_000);
System.out.println(Thread.currentThread()+": Acquire lock");
l.lock();
System.out.println(Thread.currentThread()+"; Success!");
}
}
輸出:
Thread[Thread-0,5,main]: Acquire lock
Thread[Thread-0,5,main]: Lock aquired: wait
Thread[main,5,main]: Acquire lock
Thread[Thread-0,5,main]; Exiting
// "Success" is never written: stuck in dead-lock
因此當(dāng)單獨(dú)的線程獲得鎖定,然后退出時(shí),主線程無(wú)法進(jìn)行鎖定.
總結(jié)
以上是生活随笔為你收集整理的java释放锁_java – 一个线程在完成后释放锁吗?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: (视频+图文)机器学习入门系列-第11章
- 下一篇: 为什么读博士的人越来越多?博士毕业难度不