7

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

    }
}
Alexis Leclerc
  • 1,303
  • 1
  • 16
  • 26
user3367892
  • 91
  • 2
  • 8
  • The main thread "dies" when the `main` method is exited, therefore: yes, of course. – Rafael Winterhalter Mar 12 '14 at 12:26
  • 1
    but the sample output gives "main thread is stopping" in the beginning. thats confusing – user3367892 Mar 12 '14 at 12:29
  • As soon as the Thread completes it work, that is, completes execution of run() method, Mythread releases its lock.As Main Thread just has MyThread to complete its work, so as soon as MyThread completes its execution, Main Thread also dies. – Sambhav Mar 12 '14 at 12:30
  • 1
    Are you sure about this output? – Abimaran Kugathasan Mar 12 '14 at 12:34
  • thats what the question has asked. However I think its a typo because it doesnt make sense. If the main thread stops before MyThread then Mythread wont work right? – user3367892 Mar 12 '14 at 12:44
  • 1
    if the main thread exits first, then the process is destroyed along with all the threads. That is not happening in your example. If you want to see it happening that way, just remove the line t.join() – Graham Griffiths Mar 12 '14 at 13:24

3 Answers3

2

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.

Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15
  • 1
    My sample output shows: Random no = 80 Random no = 9 Random no = 60 Random no = 24 Random no = 24 Random no = 50 Random no = 57 Random no = 25 Random no = 97 Random no = 12 Thread that generates random nos is stopping Main thread stopping Which is expected but the question has the sample output as typed in the question above. I dont know how to fix that. – user3367892 Mar 12 '14 at 12:32
  • @Graham I'd suggest adding this [Thread Interference](http://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html) reference to your answer, if you judge it appropriate. I found it quite useful to better understand that Thread order is unpredictable. – Alexis Leclerc Mar 12 '14 at 12:36
  • When I run the above code, it gives me the expected output with the expected order therefore I dont think the problem is with the order. – user3367892 Mar 12 '14 at 12:43
1

Memory Synchronization in a Multi-core System

Since both threads are being run on separate cores (most probably), the objects that the threads have access to are cached by each core (in L1 cache) for improved performance.

Whenever the state of the object is changed, all caches try to synchronize with value in RAM, which is not guarantied to occur immediately.

Some threads might be able to synchronize before other threads even if it violates happens-before relationship between them.

The reason behind this lies in the implementation of the java memory model.


The same thing is happening with System.out object here.

You can not guaranty the order in which the data is passed and flushed through it.

Therefore it is unpredictable. Calling

System.out.flush();

might improve the result, but it will not guaranty.


For more, refer to Multiple threads using System.out.println in Java

Hope this helps.

Community
  • 1
  • 1
Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45
0

The main thread exit on below situation :-

  1. Normally when program execution complete .
  2. If you are using System.exit(1).
  3. JVM crashes.

Hope it will help you.

JDGuide
  • 6,239
  • 12
  • 46
  • 64