views:

110

answers:

2

Hey there!

Here's my code:

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

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!

+8  A: 

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 */ } });
Kaleb Brasee
fascinating, don't know if I'll need this, but good to know.
Yar
But then he could only have a single thread running at once.
danben
That's what he wants I thought, only 1 Thread of that type running at any given time.
Kaleb Brasee
Yepp, that's what I want, only 1 thread running at any given time. I only need that thread to play music in the background while i can still execute any operation in the foreground.
Illes Peter
Ok, I was under the impression that you could have a variable number of other threads running, but this music-playing thread could shut them down when necessary. One problem with this approach is that if the thread currently executing in the executor is taking a long time, your music thread will have to wait for it.
danben
Unless you stop it manually, in which case I don't see any reason to use an executor in the first place.
danben
A: 

you could create a static data member for the class(where threading takes place) which is incremented each time an object of that class is called,read that and u get the number of threads started

appusajeev
that's a good idea, but then how would i close the other threads? i wouldn't have any reference to them
Illes Peter