Sirish
Sirish

Reputation: 937

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

Upvotes: 51

Views: 121150

Answers (5)

Dhwaj Sharma
Dhwaj Sharma

Reputation: 1

In this approach, the main program will create a new thread that runs the background process, and the main thread will continue executing without waiting for the background thread to complete.

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

Upvotes: 0

stefano
stefano

Reputation: 336

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

Upvotes: 17

assylias
assylias

Reputation: 328608

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
    }

Upvotes: 108

Christoph142
Christoph142

Reputation: 2632

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

Upvotes: 8

EleetGeek
EleetGeek

Reputation: 121

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

Upvotes: 10

Related Questions