请教一个问题,我想用Java做一个精确到1毫秒的秒表计时器,目前用的核心代码是这样的:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if(Mode == 0) { // 秒表模式
MsCount++;
} else { // 倒计时模式
MsCount--;
}
// 根据毫秒数计算:时、分、秒、毫秒
H = MsCount / (1000 * 60 * 60);
M = MsCount % (1000 * 60 * 60) / (1000 * 60);
S = MsCount % (1000 * 60) / 1000;
Ms = MsCount % 1000;
// 格式化输出内容:时、分、秒显示2位,毫秒显示3位
Hh = String.format("%02d", H);
Mm = String.format("%02d", M);
Ss = String.format("%02d", S);
Mss = String.format("%03d", Ms);
SwingUtilities.invokeLater(() -> { // 事件调度线程,执行和UI相关的任务
TimeUI.setText(Hh + ":" + Mm + ":" + Ss + "." + Mss);
});
if(H == 24 || MsCount == 0) { // 秒表模式到达24小时或者倒计时为0时停止计时器
timer.cancel();
timer.purge(); // 释放内存
Btn1.setText("开始");
Btn2.setEnabled(true);
SetMode.setEnabled(true);
if(MsCount == 0) {
JOptionPane.showMessageDialog(Jf, "当前倒计时模式已结束!", "提示", JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(Jf, "当前秒表模式已达最大值:24:00:00.000 !", "提示", JOptionPane.WARNING_MESSAGE);
}
}
}
}, 0, 1); // 计时器首次立即执行,后续任务间隔 1 毫秒执行一次
但是以上代码在执行的过程中会占用大量的CPU(50%以上)和内存(200MB以上)资源,考虑到精度1毫秒执行一次对系统的压力太大,尝试将Timer间隔设置为10毫秒,内存占用不变,且依旧占用15%以上的CPU资源!请问,有什么好的办法能在保持精度的前提下降低CPU和内存的资源占用吗?