我想从我的主 java 程序中生成一个 Java 线程,并且该线程应该单独执行而不干扰主程序。应该是这样的:
- 用户启动的主程序
- 做一些业务工作,应该创建一个可以处理后台进程的新线程
- 一旦创建线程,主程序不应等到生成的线程完成。事实上它应该是无缝的..
最佳答案
一种直接的方法是自己手动生成线程:
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 和执行器服务:
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
executor.shutDown(); // tell executor no more work is coming
// this line will also execute without waiting for the task to finish
}
关于java - 在java中创建线程以在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12551514/