Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Don't wait for a thread to complete

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?

like image 531
JediPotPie Avatar asked May 19 '09 14:05

JediPotPie


2 Answers

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:

  • Java Concurrency Tutorial
  • ExecutorService
  • ExecutorCompletionService
  • Runnable
  • Thread
  • Future
like image 96
Adam Jaskiewicz Avatar answered Oct 04 '22 02:10

Adam Jaskiewicz


Thread t = new Thread(new YourClassThatImplementsRunnable());
t.start();

// JDK 8
new Thread(() -> methodYouWantToRun()).start();
like image 45
PaulJWilliams Avatar answered Oct 04 '22 03:10

PaulJWilliams