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

Hak*_*ata 6 java multithreading

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

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();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*rtz 5

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

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