繁体   English   中英

Java计时器类不会自动刷新Runtime函数吗?

[英]Java timer class does not auto refresh a Runtime function?

我有用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

...相同的号码(113179200)...永远

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM