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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4005350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:12:55  来源:igfitidea点击:

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

javamultithreadingparallel-processing

提问by helpmepls

The goal is to be able to invoke execution of a separate threadfrom 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.

一些上下文:我有一个必须运行process 的程序。该进程(一个 cmd进程应该只在主程序完成执行并从内存中卸载时运行。

What code should I include in the main class?

我应该在主类中包含哪些代码?

采纳答案by Kdeveloper

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

如果您的意思是:如何启动一个不会在我的 JVM(Java 程序)结束时结束的 Java 线程?.

The answer is: you can't do that.

The answer is: you can't do that.

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

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

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 doThisVeryImportantThingwill terminate that thread. You could run it as a daemon, as in this example:

这个示例程序永远不会停止,除非有什么东西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(); 

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

这将确保,如果 main() 线程结束,它也会终止 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 启动不同的 JVM,为此您可能想查看这个问题:从 Java 应用程序启动 JVM 进程使用 Runtime.exec?

回答by Peter Lawrey

Sounds like you want a script which calls the first program and then when the first finishes, it calls the second program.

听起来你想要一个调用第一个程序的脚本,然后当第一个程序完成时,它调用第二个程序。

Something like

就像是

program1
program2

EDIT: To run the two tasks in parallel you can do

编辑:要并行运行这两个任务,您可以执行

program1 &
program2

in a bash/unit shell.

在 bash/单元外壳中。

or in dos shell

或在 dos shell 中

start program1
program2

回答by Tony Ennis

I'm not altogether sure you can make a 'detached' thread in Java using the normal means of implementing Thread and kicking it off with run().

我不完全确定您可以使用实现 Thread 的常规方法在 Java 中创建一个“分离”线程并使用 run() 启动它。

You might need to fork a thread using Runtime.exec(), running java as wholly separate process, not as a thread.

您可能需要使用 fork 来创建一个线程Runtime.exec(),将 java 作为完全独立的进程运行,而不是作为线程运行。

回答by Cameron Skinner

To spawn a process that survives after the JVM terminates you'll need to use Runtime.exec(). Since you want it to run after your main process ends, there are really two ways you can do it:

要生成在 JVM 终止后仍然存在的进程,您需要使用Runtime.exec(). 由于您希望它在主进程结束后运行,因此实际上有两种方法可以做到:

1) If you only want to process to run during a clean shutdown then you can do this:

1)如果您只想在干净关闭期间运行进程,那么您可以这样做:

public static void main(String[] args) {
    doThisProgramsStuff();
    spawnSecondProcess();
}

2) Or, if you want the process to run even with an unclean shutdown (or if it's a GUI application) then you can add a shutdown hook:

2) 或者,如果您希望进程在不干净的关闭(或者如果它是一个 GUI 应用程序)的情况下运行,那么您可以添加一个关闭钩子:

public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            spawnSecondProcess();
        }
    });
    doThisProgramsStuff();
}

There is, however, a problem with all this. Once the JVM terminates the child process will have standard input/output attached to nothing, so it might fill it's output buffers and block. You'll need to do something to make sure this doesn't happen by either making sure the process does not produce output to those streams or by doing the Windows equivalent of redirecting to /dev/null.

然而,这一切都存在问题。一旦 JVM 终止子进程将有标准输入/输出附加到任何东西,所以它可能会填充它的输出缓冲区和块。您需要做一些事情来确保不会发生这种情况,方法是确保该过程不会向这些流产生输出,或者执行与重定向到 /dev/null 的 Windows 等效操作。

回答by Peter Knego

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():

然后在你的 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.

这样您的主程序将继续运行,而您的后台线程将启动一个外部进程并在该程序退出时退出。