我想創建一個程序,說明與檢查點的馬拉松選手。創建5個跑步者,並隨機抽出時間到達第一個檢查點。跑步者必須停在檢查站,直到所有其他跑步者都到達檢查站。有2個檢查站和終點線。如何暫停Runnable直到另一個相同類型的任務完成?
這裏是我認爲將是實現這一目標的最佳途徑一些基本代碼:
public class Main {
public static void main(String[] args) {
int i = 1;
Runner[] runners = new Runner[5];
//Create 5 Runners
for (Runner runner : runners) {
runner = new Runner(i++);
runner.run();
}
//Wait for runners to arrive at 1st checkpoint
for (Runner runner : runners) {
runner.arrivedAt1stCheckpoint();
}
//Wait for runenrs to arrive at 2nd checkpoint
for (Runner runner : runners) {
runner.arrivedAt2ndCheckpoint();
}
//Wait for runners to finish race
for (Runner runner : runners) {
runner.finishedRace();
}
}}
public class Runner implements Runnable {
public final int runnerID;
Random randomGenerator = new Random();
public Runner(int i) {
this.runnerID = i;
}
@Override
public void run() {
System.out.printf("Runner %d exists\n", runnerID);
}
public boolean arrivedAt1stCheckpoint() {
sleepThread();
System.out.printf("Runner %d arrived at 1st checkpoint\n", runnerID);
return true;
}
public boolean arrivedAt2ndCheckpoint() {
System.out.printf("Runner %d arrived at 2nd checkpoint\n", runnerID);
sleepThread();
return true;
}
public boolean finishedRace() {
System.out.printf("Runner %d finished race\n", runnerID);
sleepThread();
return true;
}
private void sleepThread() {
try {
Thread.sleep(randomGenerator.nextInt(1000));
} catch (InterruptedException ex) {
Logger.getLogger(Runner.class.getName()).log(Level.SEVERE, null, ex);
}
}}
這顯然是勉強結構,我錯過了一堆的東西,所以我不要求寫整個程序對我來說。 我在這裏遇到的主要問題是讓Runner類的每個實例以某種方式與其他實例進行通信,並且休眠整個程序,直到所有Runners達到檢查點。 任何「指針」將有所幫助,謝謝!
你有沒有考慮過'CountDownLatch'? – MadProgrammer
從來沒有聽說過,我會檢查出來 – OverflowingJava
你可能想嘗試一個ForkJoinPool。看看invokeAll方法。 –