Java多线程未停止



我有一种扩展Thread类的"秒表"的以下代码:

package StopWatch;
//Code taken from:
//https://stackoverflow.com/questions/9526041/how-to-program-for-a-stopwatch
public class Stopwatch extends Thread {
private long startTime;
private boolean started;
public void startTimer() {
this.startTime = System.currentTimeMillis();
this.started = true;
this.start();
}
public void run() {
while(started){/*currentTimeMillis increases on its own */}
System.out.println("timer stopped");
}
public int[] getTime() {
long milliTime = System.currentTimeMillis() - this.startTime;
int[] time = new int[]{0,0,0,0};
time[0] = (int)(milliTime / 3600000);    //gives number of hours elapsed
time[1] = (int)(milliTime / 60000) % 60; //gives number of remaining minutes elapsed
time[2] = (int)(milliTime / 1000) % 60;  //gives number of remaining seconds elapsed
time[3] = (int)(milliTime);              //gives number of remaining milliseconds elapsed
return time;
}
public void stopTimer() {
this.started = false;
}
}

我正在以下驱动程序类中测试它:

import StopWatch.Stopwatch;
public class StopWatchTest {
public static void main(String[] args) {
Stopwatch stopwatch = new Stopwatch();
stopwatch.startTimer();
int sum = 0;
for (long i = 0; i < 100000; i++) {
sum++;
}
int[] time = stopwatch.getTime();
for (int i = 0; i < 4; i++) {
if (i < 3) {
System.out.print(time[i]+":");
} else {
System.out.print(time[i]);
}
}
stopwatch.stopTimer();
}
}

我的意图是使用类Stopwatch的实例来衡量各种代码块的性能(例如驱动程序类中的for循环(,方法是在执行我想要评估的代码块之前,让这些Stopwatchs对象在主线程中启动单独线程中的计时器,然后一旦主线程中所述块的执行完成,就让它们(Stopwatch对象(停止它们的定时器。我知道有更简单、更容易的方法可以做到这一点,但我想尝试用这种方式来做一种"概念验证",并简单地改进多线程,但我遇到了一些问题:

1( 当我运行驱动程序类StopWatchTest时,我每次都会得到看似随机和任意的输出(但大多是0:0:0:0(

2( 主线程(或者可能是Stopwatch线程,我甚至不确定了(在我得到类似0:0:0的输出后似乎永远不会停止执行

3( 当我尝试用断点等进行调试时,我会得到完全出乎意料的行为,这取决于我把断点放在哪里(主线程有时会完成执行,但会有0:0:13:2112这样的随机输出,而其他时候我只是被困在Stopwatch线程中(

第3点不像第1点和第2点那样让我担心,因为我对一个或多个线程在断点处暂停进行调试时多线程的行为了解有限(我怀疑当我中断主线程时,Stopwatch线程会继续运行(。第1点和第2点更困扰我,因为我不明白为什么会发生。

要开始,您应该将启动的布尔值标记为volatile:

private volatile boolean started;

这应该是可行的,但它会产生一个繁忙的循环,这对CPU的使用非常不利。接下来您应该查看wait()/notify()方法。

最新更新