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

在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:


  1. 用户发起的主程序

  2. 是否有一些业务工作并且应该创建一个可以处理后台进程的新线程

  3. 一旦创建了线程,主程序就不应该等到生成的线程完成。实际上它应该是无缝的..


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

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
}