Java – when does the main thread die?

The problem is to use threads to generate random numbers between 1 and 99 But the problem here is that I don't know where the "main thread stop" comes from?

This is the sample output: @ h_ 419_ 4@

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

Myth: @ h_ 419_ 4@

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 courses: @ h_ 419_ 4@

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");

    }
}

Solution

You cannot rely on the main thread and other threads to write to system Out order

To answer your question directly - the main thread waits for the thread to complete, and then it writes the message to system Out, and then it will die The only puzzling thing is that you write to system. Net from two different threads Out, so you have no guarantee of relative sorting Println from two different threads can display interleaving in any way... It just displays the output of the main thread first@ H_ 419_ 4@

As Alexis Leclerc points out - you get an unpredictable interleaving, just like in this Java threads tutorial@ H_ 419_ 4@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>