Reputation: 1068
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?
Upvotes: 10
Views: 16848
Reputation: 19225
Thread t = new Thread(new YourClassThatImplementsRunnable());
t.start();
// JDK 8
new Thread(() -> methodYouWantToRun()).start();
Upvotes: 27
Reputation: 10996
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
.
Upvotes: 11
Reputation: 21815
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.
Upvotes: 5
Reputation: 7108
basically start the thread and dont perform join. So you will not be waiting for the thread to finish.
Upvotes: 2
Reputation: 57333
public static void foo() {
new Thread() {
public void run() {
//do something here....
}
}.start();
}
Upvotes: 7