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

前端 未结 5 761
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 05:52

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 ru

5条回答
  •  我寻月下人不归
    2021-02-04 06:45

    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?

提交回复
热议问题