Illes Peter Illes Peter - 1 year ago 50
Java Question

Only one thread at a time!

Here's my code:

new Thread() {
public void run() {
try {; }
catch ( Exception e ) { System.out.println(e); }

which creates and starts a thread. I'd like to modify this code so that the thread only starts if there are no other threads open at the time! If there are I'd like to close them, and start this one. Thanks in advance!

Answer Source

You can create an ExecutorService that only allows a single thread with the Executors.newSingleThreadExecutor method. Once you get the single thread executor, you can call execute with a Runnable parameter:

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() { public void run() { /* do something */ } });