Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a new thread only if no other threads are currently open?

This code creates and starts a thread:

new Thread() {
    @Override
    public void run() {
        try { player.play(); }
        catch ( Exception e ) { System.out.println(e); }
    }
}.start();

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.

like image 572
Illes Peter Avatar asked Jan 16 '10 15:01

Illes Peter


1 Answers

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 */ } });
like image 53
Kaleb Brasee Avatar answered Nov 03 '22 09:11

Kaleb Brasee