私は複数のスレッド間の競合をシミュレートするコードを書いている中で、完成したスレッドの順序を取得し、そのレースの勝者を印刷し、スレッドの順番が終了しました。 私は勝者を決定することができましたが、私は終了し、すべてのスレッドの順序を印刷する方法を見つけ出すことはできません。ここでレースシミュレーションと勝者
は、今までのコードは、任意のヘルプです!
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Runner {
private static CountDownLatch latch = new CountDownLatch(3);
private static String winner;
public static synchronized void finished(String threadName) {
if (winner == null) {
winner = threadName;
}
latch.countDown();
}
public static void main(String[] args) throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
threadPool.submit(new raceTrack("Racer "+i));
}
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.SECONDS);
try {
latch.await();
System.out.println("The winner is : " + winner);
}
catch (InterruptedException e) {
System.out.println("No winner");
Thread.currentThread().interrupt();
}
}
}
public class raceTrack implements Runnable {
public String racerID;
public raceTrack(String id) {
this.racerID = id;
}
@Override
public void run() {
System.out.println(racerID);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
finally {
Runner.finished(racerID);
}
}
}
スタートとして決定されます。 –