如何在Java中运行与主线程分开的线程

如何在Java中运行与主线程分开的线程

本文介绍了如何在Java中运行与主线程分开的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是能够从主类内部调用单独线程的执行.

某些情况:我有一个必须运行进程的程序.进程(一个cmd一个)仅应在主程序完成执行并从内存中卸载后运行.

我应该在主类中包括什么代码?

解决方案

如果您的意思是:如何启动一个Java线程,当我的JVM(java程序)运行时,该线程不会结束?. /p>

The answer is: you can't do that.

因为在Java中,如果JVM退出,则所有线程都已完成.这是一个例子:

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

例如,可以通过以下代码从您的主线程启动以上程序:

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

该示例程序将永远不会停止,除非doThisVeryImportantThing中的某些内容将终止该线程.您可以将其作为守护程序运行,如以下示例所示:

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

这将确保,如果main()线程结束,它将终止myThread.

但是,您可以启动与Java不同的JVM,因为您可能想检查以下问题:从Java应用程序启动JVM进程使用Runtime.exec吗?

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?

解决方案

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?

这篇关于如何在Java中运行与主线程分开的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:07
查看更多