java wait 释放锁_java – 持有多个锁的线程进入wait()状态.它是否释放所有锁定锁?...

本文探讨了一个Java程序中线程锁与等待机制的问题。通过一个具体的例子展示了当一个线程持有两个不同对象的锁,并在一个对象上调用wait()方法时,另一个对象的锁是否会被释放的现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我编写了这个程序来检查线程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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值