Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..
like image 882
Sirish Avatar asked Sep 23 '12 10:09

Sirish


People also ask

How do I run a Java process in the background?

You can read the input stream(i.e br. readLine() ) in a thread. That way, it's always running in the background. ReaderThread should continue reading the output of the process you have started, as long as it lasts.

Which thread is executed in background?

Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.


1 Answers

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     } 
like image 85
assylias Avatar answered Sep 25 '22 10:09

assylias