2012-09-23 45 views
18

我想从我的主java程序中产生一个Java线程,并且该线程应该单独执行而不会干扰主程序。这是应该的:在java中创建线程以在后台运行

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

可能重复http://stackoverflow.com/questions/2865315/threads-in-java) –

+2

你看过[Java Tutorials Concurrency section](http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html)吗? – Keppil

回答

55

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

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 
} 
+1

谢谢assylias .. !!我脑海中一片空白,导致了这个非常基本的问题。但是你的代码帮助了我!谢谢。! – Sirish

+0

非常非常谢谢你! – Paolo

+0

当我看到任务管理器后台进程系统没有显示.....这是怎么回事...请放下一行只是为了帮助 –

5

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

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

,如果你喜欢做它在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"); 
    } 
} 
[Java中的线程(的