简体   繁体   中英

Can someone tell me how to create in java an array of n number of threads in a thread group?

我一直在努力寻找一些示例或Java演示,以了解如何创建属于某个线程组的n个线程的数组,因此,如果有人知道更多内容,请解释一下,谢谢。

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);
  }
  ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM