java - 在java中创建线程以在后台运行

标签 java multithreading

我想从我的主 java 程序中生成一个 Java 线程,并且该线程应该单独执行而不干扰主程序。应该是这样的:

  1. 用户启动的主程序
  2. 做一些业务工作,应该创建一个可以处理后台进程的新线程
  3. 一旦创建线程,主程序不应等到生成的线程完成。事实上它应该是无缝的..

最佳答案

一种直接的方法是自己手动生成线程:

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/

相关文章:

c++ - Linux (C++) 中的 fork 和等待。

在 C 中的 for 循环中创建多个 pthread

java - 是否可以使用 appengine 模块和云端点?

java - 实时查看...等中包含的集合中包含的集合

java - Maven 对 zip Artifact 的依赖

linux - linux perf 对于测量多线程 C 程序的缓存未命中是否准确?

java - 无法在具有等待和通知的多线程环境中从套接字输入流读取

java - 从方法返回的值可以分配给常量吗?

java - EJB 是 Java 中的 ADO.NET 等价物吗?

c# - 以相同的方法在新线程中启动