通过Java循环线程测量时间
我有一个任务,用Java创建一个比赛,使用10个不同的参与者的线程,他们将跑100米的距离,当然,获胜者是第一个跑100米的人 但是,比赛应在所有参赛者完成比赛后结束,赛后程序还应显示每个参赛者完成比赛所需的时间 我的问题是如何在程序中添加时间,因为我尝试使用2D for循环,但没有成功 这是我到目前为止的代码 另外,我的系统应该像这样: Kazim所覆盖的距离为100米40秒 Lloran所覆盖的距离为100米36秒 我一点时间都没有通过Java循环线程测量时间,java,multithreading,Java,Multithreading,我有一个任务,用Java创建一个比赛,使用10个不同的参与者的线程,他们将跑100米的距离,当然,获胜者是第一个跑100米的人 但是,比赛应在所有参赛者完成比赛后结束,赛后程序还应显示每个参赛者完成比赛所需的时间 我的问题是如何在程序中添加时间,因为我尝试使用2D for循环,但没有成功 这是我到目前为止的代码 另外,我的系统应该像这样: Kazim所覆盖的距离为100米40秒 Lloran所覆盖的距离为100米36秒 我一点时间都没有 public class Race implements
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();
}
}
公共类竞赛实现可运行
{
公共静态字符串赢家;
公开竞逐()
{
对于(int distance=1;distance请查看System.currentTimeMillis()
。如果在比赛线程开始时存储当前时间,并在结束时再次检查,则差值将给出该线程的毫秒数。在类中添加字段:
public class Race implements Runnable
{
public long timeStart, timeFinish;
public static String winner;
在run()中:
在isRaceFinished()中:
然后计算每个线程的时间间隔。这里的一个问题是,较早启动的线程可以在较后启动的线程之前开始工作-较早启动的线程几乎肯定会赢(如果不总是t1
)。您应该使用类似于倒计时闩锁
的方法来阻止线程,直到所有线程都准备就绪。另一个是您需要同步对赢家
的读/写访问,否则不能保证所有线程都会看到已设置赢家。当然,也可以使用原子引用
。我刚刚意识到我的程序m的错误远不止时间。谢谢你们的帮助,无论如何,我会记住这一点的。
public void run()
{
this.time = System.currentTimeMillis();
this.race();
}
if (winner == null && distance == 100)
{
String winnerName = Thread.currentThread().getName();
winner = winnerName;
this.timeFinish = System.currentTimeMillis();