我一直在努力研究如何创建一个Timer类,在创建该类的新对象时,该类将以毫秒为单位计算。
public class Timer implements Runnable {
private long ms;
public Timer() {
this.ms = 0;
new Thread(this).run();
}
public Timer(long ms) {
this.ms = ms;
new Thread(this).run();
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
ms++;
Time.sleep(1);
}
}
public long getElapsed() {
return ms;
}
}
这是我的Timer类,但是,当我尝试创建它的对象时:
Timer t = new Timer();
它卡在计时器内的线程上。我根本不明白我应该如何在我的主程序中连续运行一个线程。
还应该注意的是,我以此为例,因为很可能有更好的方法来创建计时器。
感谢您的时间。
答案 0 :(得分:1)
我不确定你是否真的想要在这里尝试做什么,因为这会浪费大量的CPU时间。
为什么不尝试这样的事情:
public class MyObject {
private long birthTime;
public MyObject() {
this.birthTime = System.nanoTime();
}
public long getElapsedMilliseconds() {
return (System.nanoTime() - this.birthTime) / (1000 * 1000);
}
}
可以这样使用:
public static void main(String[] args) {
MyObject obj = new MyObject();
try {
Thread.sleep(1337);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("obj is " + obj.getElapsedMilliseconds() + "ms old");
}
并将返回:
obj is 1337ms old
您只需要存储从创建MyObject
那一刻起的当前时间(以毫秒为单位),然后您可以通过再次减去当前时间(以毫秒为单位)来推断出对象的生存时间。
答案 1 :(得分:0)
而不是
new Thread(this).run()
使用
new Thread(this).start()
但正如Stefan Falk所说,最好存储System.currentTimeMillis()
并用它来计算"现场时间"你的对象。