3

I started t1 thread in my main method and want to stop main thread but my t1 thread still running. It is possible? how?

public static void main(String[] args) 
{
    Thread t1=new Thread()
    {
      public void run()
      {
          while(true)
          {
              try
              {
                  Thread.sleep(2000);
                  System.out.println("thread 1");

              }
              catch(Exception e)
              {}
          }             
      }
    };

    t1.start();    
}
Ahmad Vatani
  • 1,630
  • 4
  • 21
  • 34

4 Answers4

6

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:

• It is the thread from which other "child" threads will be spawned.
• It must be the last thread to finish execution. When the main thread stops, your program terminates.

One more thing, program terminates when all non-daemon threads die (daemon thread is a thread marked with setDaemon(true)).

Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.

public class DaemonTest {
    public static void main(String[] args) {
        new WorkerThread().start();
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }
}

public class WorkerThread extends Thread {
    public WorkerThread() {
        setDaemon(false) ;   // When false, (i.e. when it's a user thread),
                // the Worker thread continues to run.
                // When true, (i.e. when it's a daemon thread),
                // the Worker thread terminates when the main 
                // thread terminates.
    }

    public void run() {
        int count=0 ;
        while (true) {
            System.out.println("Hello from Worker "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}
aashish
  • 103
  • 2
  • 7
2

Regular Threads can prevent the VM from terminating normally (i.e. by reaching the end of the main method - you are not using System#exit() in your example, which will terminate the VM as per documentation).

For a thread to not prevent a regular VM termination, it must be declared a daemon thread via Thread#setDaemon(boolean) before starting the thread.

In your example - the main thread dies when it reaches the end of it code (after t1.start();), and the VM - including t1- dies when t1 reaches the end of its code (after the while(true) aka never or when abnormally terminating.)

Compare this question, this answer to another similar question and the documentation.

Community
  • 1
  • 1
hiergiltdiestfu
  • 2,339
  • 2
  • 25
  • 36
  • tnx for your answer, i test my question with two t1 thread and define t2 inside t1 then stop t1 and see that t2 still running, but i want to khow about main thread – Ahmad Vatani Apr 23 '14 at 10:16
  • so from your answer i understand after t1.start(); just t1 thread is running, I thought that main thread just ends by System.exit(); – Ahmad Vatani Apr 23 '14 at 10:25
  • 1
    Nah, System.exit() explicitely terminates the entire VM. A thread reaching the end of its code path is simply removed from the set of active threads for that VM which will then check if other non-daemon threads are still running. If not, it will terminate itself. If yes, it will continue running. System.exit() is not involved at all unless called explicitely (by you) :) – hiergiltdiestfu Apr 23 '14 at 11:23
0

System.exit(0) exits the the current program.

"Thread.join()" method my help you to achieve what you wanted.

Aryan
  • 1,767
  • 2
  • 22
  • 39
  • I believe Thread.join() will force main thread to wait till all other threads complete their execution. In this case he seem to stop main thread while sub thread still is running. If this is his case, Thread.join() won't help him. – svjn Apr 23 '14 at 09:57
0

You can not stop the main thread while any other thread are running. (All the child threads born out of main thread.) You can use function Thread.join() to keep the main thread waiting while other thread(s) execute.