I am learning about threads in Java and trying to understand what wait() does.
Here is a piece of code I wrote:
class Scratch {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("Inside thread");
});
thread.wait();
}
}
which gave
Exception in thread "main" java.lang.IllegalMonitorStateException: current thread is not owner
at java.base/java.lang.Object.wait0(Native Method)
at java.base/java.lang.Object.wait(Object.java:366)
at java.base/java.lang.Object.wait(Object.java:339)
at Scratch.main(scratch_125.java:8)
then I checked over the internet and found out that I needed to lock over the thread to call wait() and to lock something we need to use synchronized
.
This time, I didn’t get IllegalMonitorStateException
but the code kept running and never printed “Main thread working fine?”. However, I was expecting it to give IllegalStateException because I am directly putting it in a waiting state before running the thread using thread.start()
.
class Scratch {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("Inside thread");
});
synchronized (thread) {
thread.wait(); // keeps waiting here
}
System.out.println("Main thread working fine?"); // never reached here
}
}
When I added some debugging breakpoints I realized that the code keeps waiting at thread.wait()
. This confused me, as per my understanding main
thread should not wait for other threads if thread.join()
is not written in the code.
After some research, I found out that the thread.wait()
releases the lock from the thread. but still can’t understand why the ‘main’ thread stops executing.
Why is this code behaving like this?
Also, If I add thread.start()
then thread.wait()
has no effect. and code doesn’t wait at thread.wait()
.
class Scratch {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("Inside thread");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread.start();
synchronized (thread) {
thread.wait();
}
System.out.println("Main thread working fine?");
}
}
Why did not code wait this time?