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

2022-08-31 23:48:43

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

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

答案 1

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

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
    }

答案 2

这是使用匿名内部类创建线程的另一种方法。

    public class AnonThread {
        public static void main(String[] args) {
            System.out.println("Main thread");
            new Thread(new Runnable() {
                @Override
                public void run() {
                System.out.println("Inner Thread");
                }
            }).start();
        }
    }