0

嘿,我的代码中有这个功能:

public synchronized void finished()
{
    howManyDone++;
    log.append("Finished creating board "+this.howManyDone+"\n");
    if(howManyDone == boards.length)
        JOptionPane.showMessageDialog(log, "All Boards Were Created.","Attention",JOptionPane.WARNING_MESSAGE);
}

我想在 log.append 命令中添加 evrey 线程在 sec 中运行的数量。我试着做这个:

public synchronized void finished()
{
    long start = System.nanoTime();
    howManyDone++;
    long end = System.nanoTime();
    long estTime = end - start;
    double seconds = (double)estTime/1000000000;
}

而不是像这样打印每次的秒数:

log.append("Finished creating board " +this.howManyDone+ " in "+seconds+"\n");

但是当秒数出现时我在日志中得到的数字是这样的:6.00E-7 等等......我做错了什么?

谢谢

4

1 回答 1

0

除非您能够记下线程开始工作时的系统时间,否则无法获得总运行时间。仅仅在完成的函数开始时调用它是不够的。

对于一种解决方案,您可以创建一个Thread子类来跟踪它运行的时间,如下所示:

public class TimedThread extends Thread {

    private long startTime;
    private long endTime;

    public TimedThread(Runnable r) {
        super(r);
    }

    @Override
    public void run() {
        startTime = System.nanoTime();
        super.run();
        endTime = System.nanoTime();
    }

    public long getRunDuration() {
        return endTime - startTime;
    }
}

然后使用TimedThreads 代替Threads需要计时计算的地方(假设您可以控制该部分代码)。

于 2016-12-11T20:59:31.453 回答