java 线程 wait 释放锁,持有多重锁定的线程进入wait()状态。它会释放所有保持锁吗?...

I wrote this program to check if a thread t1 holding lock on two different objects :

Lock.class and MyThread.class goes into waiting mode on MyThread.class instance using MyThread.class.wait().It does not release lock on Lock.class instance. why so ? I have been thinking that once a thread goes into wait mode or it dies it releases all the acquired locks.

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();

}

}

}

解决方案

You are correct that it doesn't release the other lock. As for why, it's because it isn't safe to do so. If it was safe to release the outer lock during the call to the inner function, why would the inner function be called with the other lock held at all?

Having a function release a lock it didn't acquire behind the programmer's back would destroy the logic of synchronized functions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值