49

I want to spawn a Java thread from my main java program and that thread should execute separately without interfering with the main program. Here is how it should be:

  1. Main program initiated by the user
  2. Does some business work and should create a new thread that could handle the background process
  3. As soon as the thread is created, the main program shouldn't wait till the spawned thread completes. In fact it should be seamless..
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Sirish
  • 917
  • 3
  • 14
  • 25
  • 1
    possible duplicate of [Threads in Java](http://stackoverflow.com/questions/2865315/threads-in-java) – Mark Rotteveel Sep 23 '12 at 10:25
  • 3
    Have you looked at the [Java Tutorials Concurrency section](http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html)? – Keppil Sep 23 '12 at 10:28

4 Answers4

105

One straight-forward way is to manually spawn the thread yourself:

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
}

Alternatively, if you need to spawn more than one thread or need to do it repeatedly, you can use the higher level concurrent API and an executor service:

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
    }
tkruse
  • 10,222
  • 7
  • 53
  • 80
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    Thank you assylias..!! I ran out of my mind, resulting to this very basic questions. But your code helped me! Thank you.! – Sirish Sep 24 '12 at 05:45
  • When I look on the task manager background processes the system is not showing..... what about this... Please drop one line just to help – Karue Benson Karue Feb 22 '16 at 15:54
  • @KarueBensonKarue the code I posted *does* create a new thread - if you don't get that result I suggest you ask a separate question. – assylias Feb 22 '16 at 17:37
  • 1
    @Karue, the task manager shows processes, not threads. All these threads would show up under the single java process that owns them. – Barett Feb 15 '17 at 19:31
  • Would be cool if the required `import`s could be mentioned with Java answers, especially if said answer even includes a main and should be a standalone piece of code, so I don't have to hunt for them every time... – Luc Feb 05 '19 at 14:33
  • @Luc Your favourite IDE probably has an auto-import feature that should do that for you automatically. – assylias Feb 07 '19 at 13:48
  • @assylias If it could all be done automatically, I don't see why we need to clutter the source code with imports instead of having it be auto-detected JIT or compile-time. But since we have to specify it manually and there can be multiple with the same name, it would be convenient to just mention it in answers and make a working example. – Luc Feb 07 '19 at 13:58
  • What will happen if i use executor.execute(r); will it run independenly ? – LMK IND Aug 10 '20 at 17:30
17

Even Simpler, using Lambda! (Java 8) Yes, this really does work and I'm surprised no one has mentioned it.

new Thread(() -> {
    //run background code here
}).start();
stefano
  • 336
  • 2
  • 8
10

This is another way of creating a thread using an anonymous inner class.

    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();
        }
    }
EleetGeek
  • 121
  • 1
  • 5
8

And if you like to do it the Java 8 way, you can do it as simple as this:

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");
    }
}
Christoph142
  • 1,309
  • 11
  • 14
  • How does this help in spawning a thread? It won't even compile. **1.** new Thread(this::myBackgroundTask).start(); Passing method ref that returns void? **2.** `new Thread(this::myBackgroundTask).start();` `this` in `main` (static) method? The Java 8 way should have been: **Method call:** `new Thread(new Java8Thread().myBackgroundTask()).start();` **Method def:** `private Runnable myBackgroundTask() { return ()->{ //background task }; }` – adarsh Jan 17 '20 at 16:05