hibye
hibye

Reputation: 57

Threads synchronization

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) {
    
            }
        }       
    }
    

Upvotes: 1

Views: 279

Answers (2)

JJF
JJF

Reputation: 2777

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.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

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.

Upvotes: 2

Related Questions