【发布时间】:2017-02-03 02:04:27
【问题描述】:
在过去的几天里,我一直在阅读有关多线程的文章,并且遇到了一个使用多线程的简单任务。这是任务:
创建一个模拟 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() 同步,但程序也不能正常工作。你能告诉我有什么问题吗?我的错在哪里?
【问题讨论】:
标签: java multithreading synchronization