Java,不要等待线程完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/883284/
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
Java, Don't wait for a thread to complete
提问by JediPotPie
I need to find a way to spin off a thread from a static call and not wait for the thread to complete. Basically, a "fire and forget" approach. Can someone supply me with a simple example of how this can be accomplished?
我需要找到一种方法来从静态调用中分离出一个线程,而不是等待线程完成。基本上,一种“即发即忘”的方法。有人可以向我提供一个简单的例子来说明如何做到这一点吗?
回答by PaulJWilliams
Thread t = new Thread(new YourClassThatImplementsRunnable());
t.start();
// JDK 8
new Thread(() -> methodYouWantToRun()).start();
回答by Adam Jaskiewicz
If it's a long-lived thread that has a similar lifecycle to your app itself, and is going to be spending a lot of its time waiting on other threads:
如果它是一个长期存在的线程,与您的应用程序本身具有相似的生命周期,并且将花费大量时间等待其他线程:
new Thread(new yourLongRunningProcessThatImplementsRunnable()).start();
If it's a short-lived, CPU-bound task:
如果它是一个短期的、受 CPU 限制的任务:
ExecutorService es = Executors.newFixedThreadPool(Runtime.availableProcessors());
es.submit(new yourTaskThatImplementsRunnable());
Though, in most cases like this, you will be submitting a number of tasks to that same ExecutorService.
但是,在大多数情况下,您将向同一个ExecutorService.
See:
看:
回答by Steve B.
public static void foo() {
new Thread() {
public void run() {
//do something here....
}
}.start();
}
回答by Neil Coffey
Depending on the nature of your task, different ways may be approrpiate:
根据您任务的性质,可能采用不同的方法:
(1) As many have mentioned, a common way for an occasional task is simply to construct a thread and call its start()method.
(1) 正如很多人提到的,偶尔任务的一种常见方法是简单地构造一个线程并调用它的 start()方法。
(2) Remember that if your background thread doesn't stop, then by default it will prevent your program from shutting down when other threads have finished. You may therefore want to call setDaemon(true) on the threadso that it doesn't have this behaviour. (In GUI-based applications, on the other hand, you usually end up just calling System.exit() anyway, and ideally you'd buile into your long-running task a cleanway of shutting down.)
(2) 请记住,如果您的后台线程没有停止,那么默认情况下它会阻止您的程序在其他线程完成时关闭。因此,您可能希望在线程上调用 setDaemon(true) 以使其不具有此行为。(另一方面,在基于 GUI 的应用程序中,您通常最终只会调用 System.exit() ,理想情况下,您会以一种干净的方式关闭长时间运行的任务。)
(3) If you frequently have short-lived tasksto "fire and forget", then consider using the Executors frameworkavailable from Java 5 onwards.
(3) 如果您经常有短期任务需要“触发并忘记”,那么请考虑使用Java 5 以后可用的Executors 框架。
回答by Shamik
basically start the thread and dont perform join. So you will not be waiting for the thread to finish.
基本上启动线程并且不执行连接。所以你不会等待线程完成。

