45

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

  1. 用户发起的主程序
  2. 是否有一些业务工作并且应该创建一个可以处理后台进程的新线程
  3. 一旦线程被创建,主程序不应该等到产生的线程完成。其实应该是无缝的。。
4

4 回答 4

100

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

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
    }
于 2012-09-23T10:27:06.927 回答
10

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

    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();
        }
    }
于 2015-05-02T11:31:38.737 回答
8

如果你喜欢用 Java 8 的方式来做,你可以像这样简单地做:

public class Java8Thread {

    public static void main(String[] args) {
        System.out.println("Main thread");
        new Thread(this::myBackgroundTask).start();
    }

    private void myBackgroundTask() {
        System.out.println("Inner Thread");
    }
}
于 2017-08-02T13:09:02.153 回答
7

更简单,使用 Lambda!(Java 8)是的,这确实有效,我很惊讶没有人提到它。

new Thread(() -> {
    //run background code here
}).start();
于 2021-05-01T04:31:45.700 回答