我编写了这个程序,以检查线程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();
}
}
}
synchronized void a() { b(); } void b() { wait(); }
-- 是b
释放了由a
获取的锁。 - Marko Topolnika
和b
是同一接口的一部分,因此必须作为一个单元进行设计。 - David Schwartz