java - 并发创建动态线程数

标签 java multithreading parallel-processing

每次我都必须创建可变数量的线程。 为此,我创建了一个线程数组并创建了多个线程。

但是,我不明白如何启动这 n 个线程,这些线程的行为类似于多线程概念。 我希望它们并行运行。

如果在此场景中做什么,请指导。

最佳答案

But, I don't understand how to start these n number of threads behaving like multi threading concept. I want them to run in parallel.

当然可以使用循环创建线程数组:

 Thread[] threads = new Thread[NUM_JOBS_TO_CREATE];
 for (int i = 0; i < threads.length; i++) {
     threads[i] = new Thread(new Runnable() {
         public void run() {
             // some code to run in parallel
             // this could also be another class that implements Runnable
         }
     });
     threads[i].start();
 }

这将导致线程在后台并行运行。然后您可以稍后加入他们,等待他们全部完成后再继续。

// wait for the threads running in the background to finish
for (Thread thread : threads) {
    thread.join();
}

但与其自己管理线程,我建议使用内置的 Java Executors .他们为您做所有这一切,更易于管理。此方法的好处之一是它将任务 与运行它们的线程 分开。例如,您可以启动 10 个线程来并行运行 1000 个和 1000 个任务。

下面是一些示例 ExecutorService 代码:

 // create a pool of threads, 10 max jobs will execute in parallel
 ExecutorService threadPool = Executors.newFixedThreadPool(10);
 // submit jobs to be executing by the pool
 for (int i = 0; i < NUM_JOBS_TO_CREATE; i++) {
    threadPool.submit(new Runnable() {
         public void run() {
             // some code to run in parallel
             // this could also be another class that implements Runnable
         }
     });
 }
 // once you've submitted your last job to the service it should be shut down
 threadPool.shutdown();
 // wait for the threads to finish if necessary
 threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

有关详细信息,请参阅 Java tutorial on the thread executors .

关于java - 并发创建动态线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092251/

相关文章:

java - 两个文本文件中的 "words"不同,并将它们加粗,在两个txt中显示在屏幕上。文件

java - Fiddler 未捕获 Apache HttpClient 帖子

python - 调用嵌入式Python模块时,是否切换了线程?

c - 为什么这个多线程 C 程序给我段错误?

java - 导入现有的代码源并使用 Android Studio 进行编辑

java - JSON 数组中的不同对象

Java 执行器检查 TCP 连接是否有效

java - 如何在java中并行执行具有不同输入的方法的多个实例?

io - 从文本文件读取MPI

parallel-processing - CPU SIMD和GPU SIMD?