通过 for 循环测量时间 - 线程 Java



我有一个任务,使用 Threads 在 Java 中创建一场比赛,有 10 名不同的参与者,他们将跑 100 米的距离,获胜者当然是谁先到达 100 米。

但是,当所有参与者完成比赛时,比赛应该结束,并且在比赛程序之后,还应显示每个参与者完成比赛所需的时间。

我的问题是如何在程序中添加时间,因为我尝试使用 2D for 循环,但没有成功。

这是我到目前为止的代码

附言我的Syso应该喜欢像这样发短信:

卡齐姆覆盖的距离为100米40秒

洛兰覆盖的距离是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();
   }
}

看看System.currentTimeMillis() .如果您将当前时间存储在比赛线程的开头,并在结束时再次检查,则差异将为您提供该线程的毫秒数。

在类中添加字段:

public class Race implements Runnable
    {
       public long timeStart, timeFinish;
       public static String winner;

在运行():

public void run()
       {
          this.time = System.currentTimeMillis();
          this.race();
       }

In isRaceDone():

if (winner == null && distance == 100)
          {
             String winnerName = Thread.currentThread().getName();
             winner = winnerName;
             this.timeFinish = System.currentTimeMillis();

然后计算每个线程的时间间隔。

最新更新