如何在Java中进行多线程处理 [英] how to multithread in Java
本文介绍了如何在Java中进行多线程处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须多线程一个运行1000批次代码的方法。我需要将这些批次分配给不同的线程。
I have to multithread a method that runs a code in the batches of 1000 . I need to give these batches to different threads .
目前我已经产生了3个线程但是所有3个线程都在挑选第一批1000个线程。
我希望其他批次不应该选择相同的批次而是选择其他批次。
Currently i have spawn 3 threads but all 3 are picking the 1st batch of 1000 . I want that the other batches should not pick the same batch instead pick the other batch .
请帮助并提出建议。
推荐答案
我会使用ExecutorService
I would use an ExecutorService
int numberOfTasks = ....
int batchSize = 1000;
ExecutorService es = Executors.newFixedThreadPool(3);
for (int i = 0; i < numberOfTasks; i += batchSize) {
final int start = i;
final int last = Math.min(i + batchSize, numberOfTasks);
es.submit(new Runnable() {
@Override
public void run() {
for (int j = start; j < last; j++)
System.out.println(j); // do something with j
}
});
}
es.shutdown();
这篇关于如何在Java中进行多线程处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文