15

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.

divibisan
  • 11,659
  • 11
  • 40
  • 58
Illes Peter
  • 1,637
  • 5
  • 25
  • 43

3 Answers3

38

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
  • 51,193
  • 8
  • 108
  • 113
  • 1
    That's what he wants I thought, only 1 Thread of that type running at any given time. – Kaleb Brasee Jan 16 '10 at 15:22
  • 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 Jan 16 '10 at 15:25
  • 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 Jan 16 '10 at 15:28
  • Unless you stop it manually, in which case I don't see any reason to use an executor in the first place. – danben Jan 16 '10 at 15:29
4

My preferred method would be putting a synchronized keyword on the play method

synchronized play()

synchronized methods will lock the function so only one thread will be allowed to execute them at a time.

Here's some more info https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

user3466773
  • 176
  • 1
  • 2
  • 14
-6

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
  • 2,129
  • 3
  • 22
  • 20