Java 如何在新创建的线程中关闭扫描仪对象

Java 如何在新创建的线程中关闭扫描仪对象,java,multithreading,Java,Multithreading,我想创建一个定时输入程序,其中用户必须每5秒输入一个整数,但是下面的代码仅在用户及时回答所有问题时有效,但如果用户错过输入,则每个新线程创建的扫描仪对象将保持打开状态,这就是为什么当输入为7时,扫描仪对象和我无法读取我想知道是否还有其他方法可以关闭每个线程创建的scanner对象 导入java.util.* 公共类ex4{ private static class Score { public Integer maxScore; public Integer totalAttem

我想创建一个定时输入程序,其中用户必须每5秒输入一个整数,但是下面的代码仅在用户及时回答所有问题时有效,但如果用户错过输入,则每个新线程创建的扫描仪对象将保持打开状态,这就是为什么当输入为7时,扫描仪对象和我无法读取我想知道是否还有其他方法可以关闭每个线程创建的scanner对象

导入java.util.*

公共类ex4{

private static class Score {
    public Integer maxScore;
    public Integer totalAttempts;
}


public static void main(String args[]) throws Exception {
    final Score score = new Score();
    //score.maxScore = 1;
    score.maxScore = 0;
    score.totalAttempts =0;

    System.out.println("Initial maxScore: " + score.maxScore);
    while(score.totalAttempts<10) {
    Thread student = new Thread() {

        @Override
        public void run() {
            score.totalAttempts++;
            System.out.print(">");
            Scanner in = new Scanner(System.in);
            int temp =in.nextInt();
            System.out.println("you entered:"+temp);
            score.maxScore+= temp;
        }
    };

    student.start();
    Thread.sleep(5000);
    student.interrupt();
    System.out.print("\n");
    }
    System.out.println("Result maxScore: " + score.maxScore);
}

为什么要关闭扫描仪?只需退出循环,我会让线程以某种方式通知主线程,并在那里使用扫描仪。不要关闭任何在System.in上构建的扫描仪。如果关闭扫描仪,System.in也将关闭。并且您无法重新打开System.in。
whenever the user misses the 5 second window the scanner objects stack up so the output looks like this
Initial maxScore: 0
>5
you entered:5

>
>6
3
>
6
you entered:6
you entered:6
you entered:3

>
>7

>
>
>
>
Result maxScore: 20