Java:如何从主程序/类中单独运行线程? [英] Java: How to run thread separately from main program/class?
问题描述
SUBJ。如何从主类BUT分别从该类运行线程?
Subj. How to run thread from main class BUT separately from that class?
所以有一些细节:我有一个程序必须运行一个进程。该进程(一个cmd)仅在主程序完成并从内存中卸载时运行。并且只有在卸载主程序后才开始他的工作。
So a bit of details: I have one program which must run a process. That process (a cmd one) runs only when main program finished and unloaded from memory. And only after unload main program that process starting his work.
我应该在程序中添加什么?
What should I add to the program?
推荐答案
如果你意思是:如何启动一个不会在我的JVM(java程序)执行时结束的Java线程?。
答案是:你不能这样做。
因为在Java中,如果JVM退出,所有线程都完成了。这是一个例子:
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();
除非 doThisVeryImportantThing $ c中的内容,否则此示例程序将永远不会停止$ c>将终止该线程。您可以将其作为守护程序运行,如下例所示:
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();
这将确保,如果main()线程结束,它也将终止myThread。
This will make sure, if the main() thread ends, it will also terminate myThread.
但是你可以从java启动一个不同的JVM,因为你可能想看看这个问题:
从Java应用程序启动JVM进程使用Runtime.exec?
这篇关于Java:如何从主程序/类中单独运行线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!