简体   繁体   中英

when the thread will release the lock on object?

I am new for multi-threading.currently i am learning lock and notify and synchronize block . i created a small program to check how wait and notify working with synchronize block , if i will not create any thread(i supposed main thread will get the lock). Below is the code for better understanding .

public class Problem1 
{
    public void waitForSignal() throws InterruptedException
    {
        Object obj=new Object();
        synchronized (obj) {
        obj.wait();
        obj.notify();
        }
    }
    public static void main(String args[]) throws InterruptedException
    {
        Problem1 pb=new Problem1();
        pb.waitForSignal();
        System.out.println("hello");//controll not come here
    }

}

if i run the above program it will stuck. and control neither goes to notify() and nor it will exit the synchronize block. why code behave like this. i tried to search on google and i found the below statement

wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

what i understand from above statement that , for correct execution of my the program i have to create another thread, that will enter in the same monitor and interrupt the execution of the current lock holding thread. Please make me correct if i am wrong. Please me to correct above code , so it will work fine without Stuck.

When you call wait , some other thread will have to acquire the lock on obj and call notify or notifyAll to signal the waiting thread to proceed. The easiest way to understand is in the context of the Consumer/Producer problem, and Oracle has a pretty good tutorial about that .

Thread interruption is something entirely different. It is a request for the interrupted thread to check its interrupted status and terminate processing. Brian Goetz has a great article about this in the context of properly handling InterruptedException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM