I've been trying for some time to find some examples or explenations of java how to create an array of n threads that are part of some threadgroup, so if anyone knows something more please explain, thanks.
Asked
Active
Viewed 1,226 times
2 Answers
4
Sure. You can instantiate a ThreadGroup
and just pass it into the Thread
constructor:
ThreadGroup threadGroup = new ThreadGroup("somename");
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(threadGroup, someRunnable);
}
...

Gray
- 115,027
- 24
- 293
- 354
4
Why use ThreadGroup at all? Do you actually need it? Maybe all you really need is an ExecutorService that you can submit your runnables and callables to.
Being new, you might also want to take a look at Callable. It's almost like a thread, except a Callable returns a value. When you submit a callable, you get back a Future object, which is like a promise to get the value from the callable.

JohnnyK
- 1,103
- 6
- 10
-
Personally, I like creating executor services. You don't actually create threads yourself, you create Runnables and let the executor deals with running it. It's a nice way of throttling threads, too. – JohnnyK Mar 22 '12 at 19:36
-
Its also a nice way of creating queuing tasks and shutting down the pool. – Peter Lawrey Mar 22 '12 at 20:33