在過去的幾天裏,我一直在閱讀關於多線程的文章,並且使用多線程技術遇到了一個簡單的任務。這是任務:爲什麼此代碼中的同步功能無法正常工作?
創建一個模擬50米跑步比賽的應用程序(在我的代碼中他們是10,無所謂)。跑步者的數量應該是5,你應該給每個跑步者的線程命名。打印贏家。所有其他線程也應完成比賽。打印每位參賽選手完成比賽的時間並突出贏家的時間。
這是我寫的代碼:
public class Racer implements Runnable {
public static String winner;
public static int time = 0;
public void incrementTime() {
synchronized (Racer.class) {
time++;
}
}
public void race() {
for (int distance = 1; distance <= 10; distance++) {
incrementTime();
System.out.println("Distance covered by " + Thread.currentThread().getName() + " is " + distance + " meters.");
boolean finalDest = this.isTheRaceOver(distance);
if (finalDest) {
break;
}
}
}
private boolean isTheRaceOver(int finalDistance) {
boolean isRaceOver = false;
if (Racer.winner == null && finalDistance == 10) {
String winnerName = Thread.currentThread().getName();
Racer.winner = winnerName;
System.out.println("The winner is : " + Racer.winner + " with time " + time);
isRaceOver = true;
} else if (Racer.winner == null) {
isRaceOver = false;
} else if (finalDistance != 10) {
isRaceOver = false;
} else if (finalDistance == 10) {
System.out.println(Thread.currentThread().getName() + " is with time " + time);
}
return isRaceOver;
}
@Override
public void run() {
this.race();
}
}
public class RacerDemo {
public static void main(String[] args) {
Racer racer = new Racer();
Thread a = new Thread(racer, "A");
Thread b = new Thread(racer, "B");
Thread c = new Thread(racer, "C");
Thread d = new Thread(racer, "D");
Thread e = new Thread(racer, "E");
a.start();
b.start();
c.start();
d.start();
e.start();
}
}
一個輸出是:
Distance covered by A is 1 meters. Distance covered by C is 1 meters. Distance covered by C is 2 meters. Distance covered by C is 3 meters. Distance covered by C is 4 meters. Distance covered by C is 5 meters. Distance covered by C is 6 meters. Distance covered by C is 7 meters. Distance covered by C is 8 meters. Distance covered by C is 9 meters. Distance covered by C is 10 meters. The winner is : C with time 12 // should be 11 ? Distance covered by B is 1 meters. Distance covered by B is 2 meters. ...... and so on
困擾我的是,當它打印每個車手(線程)所花費的時間的事情掩蓋了距離,它並沒有顯示正確的時間。我使incrementTime()同步,但程序無法正常工作。你能告訴我什麼是錯的嗎?我的錯誤在哪裏?
這個解釋是正確的。我不知道爲什麼這是downvoted。 –
是的,我知道問題來自race(),但幾分鐘前我試圖在for循環內創建一個同步塊,它似乎正常工作..我跑了幾次..但謝謝! – Roxy