マルチスレッドプログラムサンプル
サンプルコード
5つのスレッドを立ち上げて、それぞれのスレッドで処理を実行する。サンプルなので、内部ではThread.sleepを呼び出しているだけの単純な処理。
すべてのスレッドが終了した後に、"end"という文字列を出力するため、whileループで同期を取っている。
import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; public class MultiThreadSample { public static void main(String[] args) { // 最大で5つのスレッドを起動する。 ScheduledExecutorService service = Executors.newScheduledThreadPool(5); // 別スレッドで処理する内容。 class Process implements Runnable { private int index = 0; private int i=0; public Process(int index, int i) { this.index = index; this.i = i; } @Override public void run() { try { System.out.println(Thread.currentThread().getName() + ": " + this.index); Thread.sleep(1000 * this.i); } catch (InterruptedException e) { } } } Random random = new Random(); for (int i=0; i<10; i++) { service.submit(new Process(i, random.nextInt(10))); } // 処理が完了したらスレッドを終了する。 service.shutdown(); // すべてのスレッドが終了するまで待つ。 while (!service.isTerminated()) { try { System.out.println("shutdown..."); Thread.sleep(1000); } catch (InterruptedException e) { } } System.out.println("end"); } }
実行結果1回目
pool-1-thread-1スレッドの処理は、他のスレッドの処理に比べてすぐ終わったため4回処理が呼び出されている。逆にpool-1-thread-4やpool-1-thread-5は1回しか処理が呼び出せていない。
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-4: 3
pool-1-thread-5: 4
pool-1-thread-3: 5
shutdown...
shutdown...
pool-1-thread-1: 6
shutdown...
shutdown...
shutdown...
pool-1-thread-2: 7
pool-1-thread-1: 8
shutdown...
pool-1-thread-3: 9
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
end
実行結果2回目
実行結果2回目では、1回目と異なりpool-1-thread-1は1回しか実行できていない。
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-3: 2
pool-1-thread-4: 3
pool-1-thread-5: 4
shutdown...
shutdown...
shutdown...
shutdown...
pool-1-thread-2: 5
pool-1-thread-3: 6
shutdown...
shutdown...
pool-1-thread-2: 7
shutdown...
shutdown...
pool-1-thread-5: 9
pool-1-thread-3: 8
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
shutdown...
end
Thread.sleepにはランダムで数値を渡しているため、実行するたびに出力されるメッセージは異なる。