I know a bit about multi-thread programming in java
as I know any newly created thread is attached to the current ThreadGroup by default. and if you create a new ThreadGroup, its attached as a child to current ThreadGroup.
I've written a modular program as below:
- each module is extended the class Module
- each module has its own thread pool with size of 5
- each module has its own instance of a CustomThreadGroup
- each module started in its own thread pool
- executed by invoking modules' onCreate() method in a runnable posted to its thread pool
imagine we have something like below to start each module:
for(final Module mod : modules){
mod.executor.execute(new Runnable() {
@Override
public void run() {
mod.onCreate();
}
});
}
executor is a thread pool with a custom ThreadFactory which add module's instance of CustomThreadGroup to newly created Thread by thread pool.
now I can make sure any module is launched in its own thread pool and any method invoked in onCreate is executed in the same thread. if module wants to run a long running task, it should post a new runnable to its executor or run a new Thread.
so, I can get any module's Threads recursively by invoking module's CustomThreadGroup.enumerate(n, true)
for this scenario I wrote below code:
while(true){
for(Module mod : modules){
CustomThreadGroup tg = mod.getThreadGroup();
Thread threads[] = tg.getThreads(); // invoke enumerate internally
// my tasks for classifying threads
}
Thread.sleep(5 * 1000); // sleep for 5 secs
// then recalculate threads count
}
it works well in a seperate thread to calculated threads count which will be newly created in onCreate() method of module.
so my question is:
how can I be notified about newly created threads attached to ThreadGroup without executing an infinite loop?
sorry for my bad English.