Is Java implicitly waiting for threads?

I wrote a test application that should never stop. It throws t.wait() ( t is a Thread object), but I never call a notification. Why does this code end? Despite the synchronization of the main thread by t , the spawned thread is started, so it does not block this object.

 public class ThreadWait { public static void main(String sArgs[]) throws InterruptedException { System.out.println("hello"); Thread t = new MyThread(); synchronized (t) { t.start(); Thread.sleep(5000); t.wait(); java.lang.System.out.println("main done"); } } } class MyThread extends Thread { public void run() { for (int i = 1; i <= 5; i++) { java.lang.System.out.println("" + i); try { Thread.sleep(500); } catch (Exception e) { throw new RuntimeException(e); } } } } 

As a result, the main thread waits 5 seconds, and during this time the worker gives his result. Then, after 5 seconds, the program terminates. t.wait() not waiting. If the main thread will not sleep for 5 seconds (commenting on this line), then t.wait() will actually wait for the end of the employee. Of course, join() is a method that can be used here, but, unexpectedly, wait() does the same thing as join() . Why?

Perhaps the JVM sees this, since only one thread works, there is no way to report the main thread and resolve the deadlock. If true, is this a documented feature?

I am testing Windows XP, Java 6.

+6
source share
2 answers

Waiting on Thread - and although most objects are not implicitly reported, the Thread object is notified when the thread terminates. It is documented somewhere (I'm looking for it ...) that you should not use wait / notify on Thread objects, as is done internally.

This is a good example of why it is better to use the "private" object for synchronization (and wait / notify) - something that only your code knows about. Usually I use something like:

 private final Object lock = new Object(); 

(In general, however, it’s cleaner to use some higher-level abstractions provided by java.util.concurrent if you can. As noted in the comments, it is also nice to implement Runnable rather than extending Thread yourself.)

+9
source

JavaDoc for wait gives the answer: side awakenings are possible. This means that the JVM has the right to end the wait call whenever it wants.

The documentation even gives you a solution if you don't want this (which is probably always the case): put a wait call in a loop and check if the condition you are waiting for has become true after each wakeup.

+8
source

Source: https://habr.com/ru/post/907003/


All Articles