我正在编写一个代码模拟多个线程之间的竞争并打印该竞赛的获胜者,线程的顺序完成。 我能够确定胜利者,但我无法弄清楚如何打印完成的所有线程的顺序。
这是现在的代码,Any Help !!
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);
}
}
}
答案 0 :(得分:0)
您可以拥有一个线程名称列表,而不只是一个字符串:
private static List<String> threadList;
public static synchronized void finished(String threadName) {
threadList.add(threadName);
latch.countDown();
}
然后,您可以遍历列表并确定线程的顺序。获胜者被确定为list.get(0)