java - 如何在等待控制台输入时使用 Thread.sleep() 创建计时器?

标签 java multithreading

我正在尝试编写一个程序,该程序会提出一些有时间限制的简单问题。

到目前为止,我有以下内容:

public static void main(String[]args) throws IOException, InterruptedException{
    Thread thread = new Thread();
    Scanner scan = new Scanner(System.in);

    System.out.println("1. What is 1+1?");
    System.out.println("a. 2\tb. Cannot Be.\tc. 3\td. All of the above."); 
    String question1 = scan.next();
    for(int i = 3; i>=0; i--){
        System.out.print("\b"+i);
        Thread.sleep(1000);
    }
}   

这会正确地提出问题并获取答案,但它不会对输入设置时间限制,并在给出输入后从 3 倒数到 0。我做错了什么?

最佳答案

这可以使用一点黑色多线程魔法来完成。

首先,您需要两个像这样的线程:

Thread thread1 = Thread.currentThread();
Thread thread2 = new Thread(() -> {
    try {
        for (int seconds = 3; seconds > 0; seconds--) {
            System.out.println(seconds+" second"+(seconds == 1 ? "s" : "")+" left");
            Thread.sleep(1000);
        }
        System.out.println("Time's up!");
        thread1.stop();
    }catch(InterruptedException weCanIgnoreThisException){}
});

其中 thread1 是提出问题的线程,thread2 是倒计时。

那么剩下的就是提出问题了。 不要忘记在请求输入之前start() thread2,并在收到输入后stop()它!

System.out.println("1. What is 1+1?");
System.out.println("a. 2\tb. Cannot Be.\tc. 3\td. All of the above.");
thread2.start();
String answer = scan.next();
thread2.stop();
<小时/>

好吧,这就是我使用已弃用的方法 Thread#stop() 的原因。

The official documentation of java.lang.Thread解释了为什么 stop() 被弃用,以及什么情况下它会搞砸程序:

Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.

简而言之,如果线程在使用 synchronized block 或方法锁定对象时被 stop() 执行,则该对象上的锁定将以危险的突然方式释放。由于提出多项选择题并对输入设置时间限制不需要线程在某些内容上同步,因此我们可以忽略这一点。

关于java - 如何在等待控制台输入时使用 Thread.sleep() 创建计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321588/

相关文章:

java - 扩充 java 集合以获得区间树

java - ThreadGroup.activeCount() 方法在 java 中不起作用

java - 是否可以同时读取和写入文件?

java - 调用 wait() 后有返回值是什么意思?

java - 无法比较 xml 标记中的属性

java - Google map 无法获取我的 if 语句以获得权限

java - 如何更改此主要方法以按顺序读取文件

一组的 C++ mmap

java - 退出 EDT

java - 关于java(Quartz)调度的初学者问题