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

时间:2016-03-14 12:43:13

标签: java multithreading

我有一个任务是使用具有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();

   }

}

2 个答案:

答案 0 :(得分:1)

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

答案 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();

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