在java中创建线程以在后台运行 [英] Create threads in java to run in background
本文介绍了在java中创建线程以在后台运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的主java程序中生成一个Java线程,该线程应该单独执行而不会干扰主程序。以下是它应该如何:
I want to spawn a Java thread from my main java program and that thread should execute separately without interfering with the main program. Here is how it should be:
- 用户发起的主程序
- 是否有一些业务工作并且应该创建一个可以处理后台进程的新线程
- 一旦创建了线程,主程序就不应该等到生成的线程完成。实际上它应该是无缝的..
推荐答案
一种直接的方法是手动生成线程你自己:
One straight-forward way is to manually spawn the thread yourself:
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
new Thread(r).start();
//this line will execute immediately, not waiting for your task to complete
}
或者,如果您需要生成多个线程或需要重复执行,您可以使用更高级别的并发API和执行程序服务:
Alternatively, if you need to spawn more than one thread or need to do it repeatedly, you can use the higher level concurrent API and an executor service:
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(r);
//this line will execute immediately, not waiting for your task to complete
}
这篇关于在java中创建线程以在后台运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文