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.
source share