gpt4 book ai didi

Java定时器类不会自动刷新运行时函数?

转载 作者:行者123 更新时间:2023-12-02 02:52:50 25 4
gpt4 key购买 nike

我用java编写了这个计时器函数。

    import java.util.Timer;  //Libraries used
import java.util.TimerTask;

public static void main(String[] args) {
Timer clock = new Timer();
clock.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());

}
}, 1*1*1000, 1*1*1000);// One second intervals
}

我得到这个结果(以位为单位):

115224312

113179200

113179200

...Same number(113179200)...forever

我希望此功能自动刷新并更改数字,但它没有这样做。我不确定为什么。我尝试过其他方法(循环、其他计时器等),但这些方法也不起作用。

最佳答案

在您开始计时器检查后,我用一些内存使用更新了您的代码:

public static void main(String[] args) {
Timer clock = new Timer();
clock.schedule(new TimerTask() {
@Override
public void run() {
System.out.print("Total: " + Runtime.getRuntime().totalMemory());
System.out.println(" Free: " + Runtime.getRuntime().freeMemory());

}
}, 1*1*1000, 1*1*1000);// One second intervals

// now use memory
ArrayList<Object> arrays = new ArrayList<>();
for (int i = 0; i < 1_000_000; ++i) {
ArrayList<String> strings = new ArrayList<>();
for (int j = 0; j < 1_000_000; ++j) {
strings.add("" + j);
}
arrays.add(strings);
}
System.out.println("Loop complete");
}

这是一些输出:

Total: 1203240960 Free: 752378848
Total: 1785200640 Free: 1107948136
Total: 3265265664 Free: 1522323408
Total: 3642228736 Free: 1180813496
Total: 5323096064 Free: 1982845016
Total: 5456265216 Free: 1627489984
Total: 7387742208 Free: 2923462928
Total: 7571767296 Free: 2455798264
Total: 7579631616 Free: 1657495280

如您所见,可用内存量(以及总内存)正在发生变化。

关于Java定时器类不会自动刷新运行时函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com