【问题标题】:start and stop time to schedule and run all the threads in java开始和停止时间来安排和运行java中的所有线程
【发布时间】:2016-09-01 06:01:06
【问题描述】:

我有下面的尝试方法,我需要弄清楚如何获得开始和停止时间来安排所有线程并打印出时间。

我知道如何获取实际运行时间,只是不知道如何打印线程启动所用的时间。谢谢。

void run() {
    long startTime = System.currentTimeMillis();

    Code goes here.....

    long endTime = System.currentTimeMillis();

    NumberFormat formatter = new DecimalFormat("#0.00000");
    System.out.println("Execution time is " + formatter.format((endTime - startTime) / 1000d) + " seconds");        
}

【问题讨论】:

  • 请提供详细示例,我认为您的问题是,您想测量从启动线程到实际运行方法执行所花费的时间。对吗?
  • 提示:测量时间时,使用System.nanoTime()

标签: java multithreading time


【解决方案1】:

你的意思是这样的?

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MyThread extends Thread {

    ThreadLocal<Long> timeAtStart = new ThreadLocal<Long>;

    @Override
    public synchronized void start() {
        //override start method and print time when start method was invoked
        timeAtStart.set(System.currentTimeMillis());
        super.start();
    }

    @Override
    public void run() {
        long timeToRun = System.currentTimeMillis();
        NumberFormat formatter = new DecimalFormat("#0.00000");
        System.out.println("Starting thread took " + formatter.format((timeToRun - timeAtStart.get()) / 1000d) + " seconds");

        //Code goes here.....

        long endTime = System.currentTimeMillis();
        System.out.println("Execution time is " + formatter.format((endTime - timeToRun) / 1000d) + " seconds");
    }
}

谢谢。

【讨论】:

    猜你喜欢
    • 2012-12-24
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多