views:

625

answers:

5

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?

+15  A: 
Thread t = new Thread(new YourClassThatImplementsRunnable());
t.start();
Visage
+4  A: 
public static void foo() {
 new Thread() {
  public void run() {
                     //do something here....
  }
 }.start();
}
Steve B.
But if the task is relatively simple, use the Runnable constructor for Thread (that is, new Thread(new Runnable() { public void run() { ... } })), since that way you're not extending a complicated class, but implementing an interface, which should be simpler in the bytecode and you won't have any name clashes with the methods in Thread.
Gracenotes
+2  A: 

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

Shamik
+4  A: 

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:

Adam Jaskiewicz
+1  A: 

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.

Neil Coffey