Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can the main thread die before the child thread

I believe that the main thread cannot die before the child thread. But is there any way to check that ? I wrote a simple program below. Can anyone prove it practically leaving theory aside ?

class childre extends Thread
{   
    public void run()
    {   
        for( int i=0 ; i<10 ;i++)
        {
            System.out.println( " child " + i);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    }
}

public class ChildThreadb4main
{

/**
 * @param args
 */
    public static void main(String[] args)
    {
    // TODO Auto-generated method stub

        System.out.println("main");

        childre c1 = new childre();

        c1.start();
        for(int i=0;i<5;i++)
        {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println( " child thread alive ? " + c1.isAlive());
    }
}

After suggestion from James. I tried the following program.

public class MainChildDie {

    public static void main(String ar[]){

        final Thread mainThread = Thread.currentThread();
        System.out.println("main run ");

        new Thread(){           

            public void run(){

                Thread childThread= Thread.currentThread();
                for(int i=0; i<10;i++){
                    System.out.println( "child"+i);

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("main alive  " + mainThread.isAlive());
            }
        }.start();      
    }
}
like image 682
randeepsp Avatar asked Jan 09 '12 05:01

randeepsp


People also ask

What happens to child thread if parent dies?

After thread completes its task by executing the code specified in the run() method, it will get killed. Here's another example which shows that if the parent thread dies, the child threads will also die.

What happens when main thread exits?

Exiting the main thread will not result in the process exiting if there are any other threads still active. According to the old-fashioned model of how processes exit, a process was in control of all its threads and could mediate the shutdown of those threads, thereby controlling the shutdown of the process.

Why is it important for the main thread to terminate at the end?

Often, it must be the last thread to finish execution because it performs various shutdown actions.

What happens when the main thread stops running in a multi threaded program?

2: It must be the last thread to finish execution. When the main thread stops, your program terminates.


2 Answers

From http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html :

The Java Virtual Machine continues to execute threads until either of the following occurs:

  1. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.

  2. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

In your case, when the main thread dies, the JVM does not exit, because you still have the created threads running, and they're daemon by default, because of this:

The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.

Cite: http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean)

like image 102
James Avatar answered Oct 15 '22 08:10

James


While the code is executing, take a Full Thread dump and see what all Threads are active.

class AnotherClass {
    public static void main(String arrp[]) throws Exception {
        Thread t = new Thread() {
            public void run() {
                while (true) {
                        // do nothing
                }
            }
        };
        t.start();
            //Sleep for 15 seconds
        Thread.sleep(15000);
    }
}

Compile and Execute it:

$ javac AnotherClass.java
$ java AnotherClass

Find the process:

$ ps -ef | grep AnotherClass

nikunj <<10720>> 10681   2 12:01:02 pts/9       0:04 java AnotherClass
nikunj 10722 10693   0 12:01:05 pts/6       0:00 grep Another

Take the Thread dump:

$ kill -3 <<10720>> 

Output (excerpts):

"main" prio=10 tid=0x00039330 nid=0x1 waiting on condition [0xffbfe000..0xffbfe2a8]
    at java.lang.Thread.sleep(Native Method)
    at AnotherClass.main(AnotherClass.java:12)

"Thread-0" prio=10 tid=0x00a1b770 nid=0x12 runnable [0xadc7f000..0xadc7f970]
    at AnotherClass$1.run(AnotherClass.java:7)

Take Another Thread dump (after 15 seconds):

$ kill -3 <<10720>> 

New Output (excerpts):

"Thread-0" prio=10 tid=0x00a1b770 nid=0x12 runnable [0xadc7f000..0xadc7f970]
    at AnotherClass$1.run(AnotherClass.java:7)

Conclusion: main is gone.

like image 23
Nikunj Lahoti Avatar answered Oct 15 '22 10:10

Nikunj Lahoti