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:
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With