問題の説明:
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "...." + i);
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "...." + i);
}
}
});
thread1.start();
thread2.start();
結果:注文を実行可視複数のスレッドが存在しません
Thread-1....0
Thread-1....1
Thread-1....2
Thread-2....0
Thread-1....3
Thread-1....4
Thread-1....5
Thread-1....6
方法1:参加
説明:waitメソッドは、Objectクラスのソース・コードの実行に参加します。原則では、メインスレッドが終了するまで継続する子スレッドの実行を知って、待機中のメインスレッドです。
thread1.start();
thread1.join();
thread2.start();
thread2.join();
方法2:単一スレッドプールExecutors.newSingleThreadExecutorを使用して()
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(thread1);
executor.submit(thread2);
executor.submit(thread3);
executor.shutdown();