就内存和性能而言,在Java中每秒打印格式化的日期和时间的最有效方法是什么?

我可以想到两种选择:

选项1:

public class TimestampFormatter {

    private static SimpleDateFormat dateFormatter = 
            new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    private static Date date = new Date();

    public static String get() {
        date.setTime(System.currentTimeMillis());
        return dateFormatter.format(date);
    }
}

选项2:

public class TimestampFormatter {

    private static SimpleDateFormat dateFormatter = 
            new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    public static String get() {
        return dateFormatter.format(new Date());
    }
}

然后使用此循环每秒打印格式化的日期和时间:

new Thread(() -> {
            while (true) {
                System.out.println(TimestampFormatter.get());
                Sleep.millis(1000);
            }
        }).start();

我认为第一种选择是这里两者中的最佳选择,但是谁能想到更好的方法?

jinjbnu 回答:就内存和性能而言,在Java中每秒打印格式化的日期和时间的最有效方法是什么?

第二个选项可能比第一个更有效(或者第一个选项 无限地仿真 更好-我怀疑您是否可以衡量任何差异)。 不管,我都希望使用 newer java.time.format.DateTimeFormatterjava.time.LocalDateTime,而不是久已弃用的SimpleDateFormatDate类。同样,安排重复的Timer而不是使用while循环并重复睡眠调用会更有效。像

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
TimerTask task = new TimerTask() {
    public void run() {
        System.out.println(dtf.format(LocalDateTime.now()));
    }
};
Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task,TimeUnit.SECONDS.toMillis(0),TimeUnit.SECONDS.toMillis(1));
本文链接:https://www.f2er.com/2954777.html

大家都在问