1

これは私のコードを単純化したものです。

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

someMethod()実行に時間がかかるため、マルチスレッドを使用してforループを100の5つの間隔に分割します。

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 に答える