Tutorial :Java, Don't wait for a thread to complete



Question:

I need to find a way to spin off a thread from a static call and not wait for the thread to complete. Basically, a "fire and forget" approach. Can someone supply me with a simple example of how this can be accomplished?


Solution:1

Thread t = new Thread(new YourClassThatImplementsRunnable());  t.start();    // JDK 8  new Thread(() -> methodYouWantToRun()).start();  


Solution:2

If it's a long-lived thread that has a similar lifecycle to your app itself, and is going to be spending a lot of its time waiting on other threads:

new Thread(new yourLongRunningProcessThatImplementsRunnable()).start();  

If it's a short-lived, CPU-bound task:

ExecutorService es = Executors.newFixedThreadPool(Runtime.availableProcessors());  es.submit(new yourTaskThatImplementsRunnable());  

Though, in most cases like this, you will be submitting a number of tasks to that same ExecutorService.

See:


Solution:3

public static void foo() {      new Thread() {          public void run() {                       //do something here....          }      }.start();  }  


Solution:4

Depending on the nature of your task, different ways may be approrpiate:

(1) As many have mentioned, a common way for an occasional task is simply to construct a thread and call its start() method.

(2) Remember that if your background thread doesn't stop, then by default it will prevent your program from shutting down when other threads have finished. You may therefore want to call setDaemon(true) on the thread so that it doesn't have this behaviour. (In GUI-based applications, on the other hand, you usually end up just calling System.exit() anyway, and ideally you'd buile into your long-running task a clean way of shutting down.)

(3) If you frequently have short-lived tasks to "fire and forget", then consider using the Executors framework available from Java 5 onwards.


Solution:5

basically start the thread and dont perform join. So you will not be waiting for the thread to finish.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »