我有一个任务是使用具有10个不同参与者的线程在Java中创建一个比赛,这个参与者将跑100米的距离,而胜利者当然是谁首先获得100米。
然而,比赛应该在所有参赛者完成比赛后结束,比赛结束后比赛计划也应该显示每位参赛者完成比赛所需的时间。
我的问题是如何在程序中添加时间,因为我尝试使用2D for循环,但没有成功。
这是我到目前为止的代码
P.S My Syso应该喜欢这样的事情:
Kazim所涵盖的距离为100米和40秒
Lloran所涵盖的距离为100米和36秒。
我还没有实现时间
public class Race implements Runnable
{
public static String winner;
public void race()
{
for (int distance = 1; distance <= 100; distance++)
{
System.out.println("Distance covered is by" + " "
+ Thread.currentThread().getName() + " is" + " " + distance);
boolean isRaceFinished = this.isRaceFinished(distance);
if (isRaceFinished)
{
break;
}
}
}
private boolean isRaceFinished(int distance)
{
boolean isRaceFinished = false;
if (winner == null && distance == 100)
{
String winnerName = Thread.currentThread().getName();
winner = winnerName;
System.out.println("The winner is" + " " + winner);
}
else if (winner == null)
{
isRaceFinished = false;
}
else if (winner != null)
{
isRaceFinished = true;
}
return isRaceFinished;
}
@Override
public void run()
{
this.race();
}
}
public class Main
{
public static void main(String[] args)
{
Race race = new Race();
Thread t1 = new Thread(race, "Dean");
Thread t2 = new Thread(race, "Lloran");
Thread t3 = new Thread(race, "Vinsel");
Thread t4 = new Thread(race, "Jimmy");
Thread t5 = new Thread(race, "Khan");
Thread t6 = new Thread(race, "Kazim");
Thread t7 = new Thread(race, "Richards");
Thread t8 = new Thread(race, "Malvo");
Thread t9 = new Thread(race, "Leddan");
Thread t10 = new Thread(race, "Joseph");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
答案 0 :(得分:1)
答案 1 :(得分:1)
在课堂上添加字段:
public class Race implements Runnable
{
public long timeStart, timeFinish;
public static String winner;
在run()中:
public void run()
{
this.time = System.currentTimeMillis();
this.race();
}
在isRaceFinished()中:
if (winner == null && distance == 100)
{
String winnerName = Thread.currentThread().getName();
winner = winnerName;
this.timeFinish = System.currentTimeMillis();
然后计算每个线程的时间间隔。