I put a bunch of runnable objects into an ExecutorService:
// simplified content of main method
ExecutorService threadPool = Executors.newCachedThreadPool();
From the javadoc for Executors.newCachedThreadPool()
:
Threads that have not been used for sixty seconds are terminated and removed from the cache.
It is usually a good idea to call shutdown()
on an ExecutorService
if you know that no new tasks will be submitted to it. Then all tasks in the queue will complete, but the service will then shut down immediately.
(Alternately, if you don't care if all the tasks complete - for example, if they are handling background calculations that are irrelevant once your main UI is gone - then you can create a ThreadFactory
that sets all the threads in that pool to be daemon.)