1

这是我的代码的简化:

for(int i = 0; i < 500; i++) {
    someMethod(i);
}

someMethod()执行需要很长时间,所以我想使用多线程将 for 循环分解为 5 个 100 的间隔:

for(int i = 0; i < 100; i++) {
    someMethod(i);
}

for(int i = 100; i < 200; i++) {
    someMethod(i);
}

...

for(int i = 400; i < 500; i++) {
    someMethod(i);
}

所以我可以someMethod()同时执行不同的i.

如何使用多线程来完成此任务?

请帮忙!谢谢!

4

1 回答 1

9

建议在ExecutorService这种情况下使用出色的代码。您所做的是将所有任务(0 到 499)提交到线程池中,它们将由池中的 5 个线程同时运行。

类似于以下内容:

// create a thread pool with 5 workers
ExecutorService threadPool = Executors.newFixedThreadPool(5);
// submit all of your jobs here
for (int i = 0; i < 500; i++) {
    threadPool.submit(new MyJob(i));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// if you need to wait for the pool you can do
threadPool.awaitTerminatation(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

private static class MyJob implements Runnable {
   private int i;
   public MyJob(int i) {
       this.i = i;
   }
   public void run() {
       // do the thread stuff here
   }
}
于 2012-07-26T20:52:33.403 回答