Search code examples
javamultithreading

Create threads in java to run in background


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..

Solution

  • 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
        }