Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a thread separate from main thread in Java?

The goal is to be able to invoke execution of a separate thread from within the main class.

Some context: I have a program that must run a process. The process (a cmd one) should run only when the main program is done executing and is unloaded from memory.

What code should I include in the main class?

like image 594
helpmepls Avatar asked Oct 23 '10 18:10

helpmepls


People also ask

How do I make one thread run after another?

By using join you can ensure running of a thread one after another.

How Stop main thread while another thread is running?

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.

What is the run () method of thread class?

The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed.


2 Answers

If you mean: how can I start a Java thread that will not end when my JVM (java program) does?.

The answer is: you can't do that.

Because in Java, if the JVM exits, all threads are done. This is an example:

class MyRunnable implements Runnable { 
   public void run() { 
       while ( true ) { 
           doThisVeryImportantThing(); 
       } 
   } 
} 

The above program can be started from your main thread by, for example, this code:

MyRunnable myRunnable = new MyRunnable(); 
Thread myThread = new Thread(myRunnable);
myThread.start(); 

This example program will never stop, unless something in doThisVeryImportantThing will terminate that thread. You could run it as a daemon, as in this example:

MyRunnable myRunnable = new MyRunnable(); 
Thread myThread = new Thread(myRunnable);
myThread.setDaemon(true); // important, otherwise JVM does not exit at end of main()
myThread.start(); 

This will make sure, if the main() thread ends, it will also terminate myThread.

You can however start a different JVM from java, for that you might want to check out this question: Launch JVM process from a Java application use Runtime.exec?

like image 148
Kdeveloper Avatar answered Oct 25 '22 11:10

Kdeveloper


Create a separate thread that executes your external program:

class MyRunner implements Runnable{
  public void run(){
     Runtime.exec("your cmd")
  }
}

then start the thread in your main():

MyRunner myRunner = new MyRunner(); 
Thread myThread = new Thread(myRunner);
myThread.start();

This way your main program will continue running, while your background thread will start an external process and exit when this program exits.

like image 27
Peter Knego Avatar answered Oct 25 '22 09:10

Peter Knego