在过去的几天里,我一直在阅读有关多线程的文章,并遇到了一个使用多线程的简单任务。这是任务:
创建一个应用程序,模拟50米(在我的代码中它们是10米,不重要)的赛跑。运动员数量应为5人,您应该为每个运动员线程命名。打印获胜者。所有其他线程也应完成比赛。打印每个运动员完成比赛所需的时间,并突出显示获胜者的时间。
这是我编写的代码:
创建一个应用程序,模拟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();
}
}
其中一个输出结果为:
A跑了1米 C跑了1米 C跑了2米 C跑了3米 C跑了4米 C跑了5米 C跑了6米 C跑了7米 C跑了8米 C跑了9米 C跑了10米 胜利者是:C,时间为12 // 应该是11吗? B跑了1米 B跑了2米 ......等等
问题在于,当程序打印每个选手(线程)所用的时间时,它显示的时间不正确。我已将incrementTime()同步化,但程序仍然无法正常工作。你能告诉我错在哪里吗?我的错误在哪里?