是否可以在Java中在后台运行计时器?

时间:2018-04-29 03:02:29

标签: java timer

我想在Java中使用后台运行计时器,从在终端上显示或打印消息的那一刻开始,直到用户在输入字符串后按下输入的那一刻。有可能这样做吗?如果是,那怎么办?

1 个答案:

答案 0 :(得分:0)

示例代码,用于获取用户输入的时间(以秒为单位)。

import java.util.Scanner;

public class StopWatchDemo {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please type a message: ");

        long start = System.currentTimeMillis();
        String input = scanner.nextLine();
        long end = System.currentTimeMillis();

        double elapsedSeconds = (end - start) / 1000.0;
        System.out.println("User input: " + input);
        System.out.println("Time taken (sec): " + elapsedSeconds);
    }
}

运行输出

Please type a message: 
This is a user message <press Enter key>
User input: This is a user message
Time taken (sec): 10.106