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.
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 usingThreadGroup#activeCount(). Simply add a condition in ThreadA to only invoke performAction() if yourpublic static ThreadC.threadGroupfield returns 0 when activeCount() is called upon it.