1

I have a thread, A, which performs periodic actions inside a while(running) loop. I then have another thread,B, which listens for user input. When the user presses a button, thread B spawns a new thread to perform a task (let's call it an instance of Thread C). This task involves sending information over the internet and can take up to 20 seconds. There can be more than one instance of C active at once.

The problem I am having is this. I would like thread A to only run it's code if there are no threads of type 'C' currently active. To be more clear, thread A looks something like this:

 class ThreadA extends Thread{

      public void run(){
            while(running){
                performAction();
                Thread.sleep(1000);
            }
      }
 }

If an instance of C is detected, then obviously I would not like performAction() to be called. If the thread is currently executing performAction(), then I would like to stop its execution at its current progress.

I'm not sure how to proceed, as I'm not sure how I would obtain a reference of the spawned threads from inside thread A.

Roger Jarvis
  • 434
  • 5
  • 20
  • 1
    This [answer](http://stackoverflow.com/a/1323480/187492) shows you how to loop through a list of running threads. – Martin May 10 '12 at 23:26

1 Answers1

2

Use java.lang.ThreadGroup. By constructing all instances of ThreadC with a static ThreadGroup, you can maintain all of the instances of ThreadC and get a count of the active ones using ThreadGroup#activeCount(). Simply add a condition in ThreadA to only invoke performAction() if your public static ThreadC.threadGroup field returns 0 when activeCount() is called upon it.

FThompson
  • 28,352
  • 13
  • 60
  • 93