Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does the main thread die?

The question was to generate random numbers between 1 and 99 using a thread. However the problem here is I don't know where does the "main thread is stopping" coming from? Doesn't the main thread die in the end?

This is the sample output:

Main thread stopping
Random no = 57
Random no = 47
Random no = 96
Random no = 25
Random no = 74
Random no = 15
Random no = 46
Random no = 90
Random no = 52
Random no = 97
Thread that generates random nos is stopping

Mythread class:

public class MyThread extends Thread {
    MyThread() {
        // default constructor
    }

    MyThread(String threadName) {
        super(threadName); // Initialize thread.
        start();
    }

    public void run() {
        // System.out.println(Thread.currentThread().getName());
        Random rand = new Random();
        int newValue;
        for (int i = 0; i < 10; i++) {
            newValue = rand.nextInt(99);// generates any vale between 1 to 99
            System.out.println("Random no = " + newValue);
        }
        System.out.println("Thread that generates random nos is stopping");

    }
}

Main class:

public class HW5ex2a {
    public static void main(String[] args) throws InterruptedException {
        MyThread t = new MyThread();
        t.start();
        t.join();// wait for the thread t to die

        System.out.println("Main thread stopping");

    }
}
like image 454
user3367892 Avatar asked Mar 12 '14 12:03

user3367892


1 Answers

You can't rely on the order that main thread and other threads write to System.out. Your thread t executes fine, the main thread waits for it to finish and then the main thread exits, all as expected. But this isn't reflected in the order that you see on System.out.

To directly answer your question - the main thread waits for the thread to finish, then it writes a message to System.out, then it dies. The only confusing thing is that, because you are writing to System.out from two different threads, you don't have any guarantees about the relative ordering. Println's from the two different threads could show up interleaved in any way...it just happens to show up with the output from the main thread first.

As Alexis Leclerc points out - you get an unpredictable interleaving, the same as in this java threads tutorial.

like image 59
Graham Griffiths Avatar answered Oct 11 '22 14:10

Graham Griffiths