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

问题描述 投票:0回答:5

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

  1. 用户发起的主程序
  2. 做一些业务工作,应该创建一个可以处理后台进程的新线程
  3. 一旦创建了线程,主程序就不应该等到生成的线程完成。事实上它应该是无缝的..
java multithreading
5个回答
108
投票

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

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
    }

17
投票

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

new Thread(() -> {
    //run background code here
}).start();

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();
        }
    }

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");
    }
}

0
投票

在这种方法中,主程序将创建一个新的线程来运行后台进程,并且主线程将继续执行而不等待后台线程完成。

public class MainProgram {

    public static void main(String[] args) {
        System.out.println("Main program started");

        // Create a new thread for the background task
        Thread backgroundThread = new Thread(new Runnable() {
            @Override
            public void run() {
                // Simulate some background work
                try {
                    for (int i = 0; i < 5; i++) {
                        System.out.println("Background thread is working: " + i);
                        Thread.sleep(1000); // Sleep to simulate work
                    }
                    System.out.println("Background task completed");
                } catch (InterruptedException e) {
                    System.out.println("Background thread interrupted");
                }
            }
        });

        // Start the background thread
        backgroundThread.start();

        // Main thread continues without waiting
        System.out.println("Main program continues without waiting for background task");

        // Simulate some other business logic in the main thread
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println("Main program is working: " + i);
                Thread.sleep(500); // Sleep to simulate work
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted");
        }

        System.out.println("Main program completed");
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.