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

2024-03-04

我想从我的主 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
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在java中创建线程在后台运行 的相关文章

随机推荐