1

The following code creates a new costum Thread and waits for the thread to end and only then the main thread gets active again.

  1. I don't quite understand how it works. Why doesn't mythread.wait(); get called immediatlly?
  2. Why not using Thread.join() instead?

    public static void main(String[] args) {

        Thread mythread = new MyThread("hello");
        mythread.start();
        synchronized (mythread) {
            try {
                mythread.wait();
            } catch (InterruptedException e) {
    
            }
        }       
    }
    
hibye
  • 57
  • 6
  • Without code of `MyThread` class it's hard to tell... – Victor Sorokin Oct 21 '15 at 15:43
  • You can ignore the implementation. It's just a thread making some "work" (basically sleeps for a few seconds and that's it) – hibye Oct 21 '15 at 15:43
  • Then, acutally, I've expected this code to block indefinitely, since there's no-one to call `mythread.notify()`. But program finishes on Linux system, I presume, because of 'spurious wakeps': http://stackoverflow.com/questions/1050592/do-spurious-wakeups-actually-happen. – Victor Sorokin Oct 21 '15 at 15:49
  • 1
    @VictorSorokin it's not a spurious wakeup. See my answer. – JB Nizet Oct 21 '15 at 16:06
  • If you want to wait for a thread to finish, call `t.join()`. If you want to start a thread, and then immediately join it without doing anything in between, then what's the point? Why even bother using a thread? – Solomon Slow Oct 21 '15 at 17:16

2 Answers2

2

When a thread has finished running, it calls notifyAll() on itself. That's how Thread.join() is implemented: it waits on the thread. So, since your main thread waits on the thread, as soon as it finishes running, the main thread is notified, and can continue executing.

You're violating a documented rule: you should never wait on a Thread object. You also violate another one: wait() should always be called inside a loop checking for a condition.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thank you. btw, what's the use of `synchronized ` here anyway? – hibye Oct 23 '15 at 12:49
  • You can not call wait() on an object without holding its object monitor. That's why synchronized is necessary. This is also documented in the javadoc of Object.wait(). Why don't you read it? – JB Nizet Oct 23 '15 at 12:52
1

The way it is working is that when myThread terminates it calls notifyAll() which wakes up your myThead.wait(). Check the java documentation for the Thread.join() method where it references its implementation.

See Java synchronization is doing auto notify on exit ? Is this expected?

Why not use join instead? I think you should. Less code you have to write. It's really not much more than what you've implemented here and other people reading your code are probably more familiar with using that call to wait on thread exit.

Community
  • 1
  • 1
JJF
  • 2,681
  • 2
  • 18
  • 31