gpt4 book ai didi

java - 持有多个锁的线程进入 wait() 状态。它会释放所有持有的锁吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:25 27 4
gpt4 key购买 nike

我编写这个程序是为了检查线程 t1 是否持有两个不同对象的锁:Lock.class 和 MyThread.class 使用 MyThread.class.wait() 在 MyThread.class 实例上进入等待模式。它不会释放 Lock.class 实例上的锁。为什么这样 ?我一直在想,一旦一个线程进入等待模式或者它死了,它就会释放所有获得的锁。

public class Lock {

protected static volatile boolean STOP = true;
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread t1 = new Thread(myThread);
t1.start();
while(STOP){
}
System.out.println("After while loop");
/*
*
*/
Thread.sleep(1000*60*2);
/*
* Main thread should be Blocked.
*/
System.out.println("now calling Check()-> perhaps i would be blocked. t1 is holding lock on class instance.");
check();
}

public static synchronized void check(){
System.out.println("inside Lock.check()");
String threadName = Thread.currentThread().getName();
System.out.println("inside Lock.Check() method : CurrrentThreadName : "+ threadName);
}
}


class MyThread implements Runnable{
public MyThread() {
}

@Override
public void run() {
try {
System.out.println("inside Mythread's run()");
classLocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static synchronized void classLocking() throws InterruptedException{
System.out.println("inside Mythread.classLocking()");
String threadName = Thread.currentThread().getName();
System.out.println("inside MyThread.classLocking() : CurrrentThreadName : "+ threadName);
/*
* outer class locking
*/
synchronized (Lock.class) {
System.out.println("I got lock on Lock.class definition");
Lock.STOP = false;
/*
* Outer class lock is not released. Lock on MyThread.class instance is released.
*/
MyThread.class.wait();
}
}
}

最佳答案

你是对的,它没有释放另一个锁。至于为什么,是因为这样做不安全。如果在调用内部函数期间释放外部锁是安全的,为什么要在调用内部函数时保持另一个锁?

让一个函数释放一个它不是在程序员背后获得的锁会破坏同步函数的逻辑。

关于java - 持有多个锁的线程进入 wait() 状态。它会释放所有持有的锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11494542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com