我一直在练习线程,所以我写了这个定时游戏,用户需要猜测正确的数字(范围从1-10)。如果用户在时间限制内猜到了正确答案,则线程停止并且程序终止。当用户在时间限制内未能猜出时,它无法工作。即使它在时间限制之后进入if语句,它仍然不能完全中断该线程,除非我猜想正确的数字。我已阅读其他线程,但他们似乎使用询问有关“传统”猜谜游戏或利用Timer
。对于建议的解决方案的解释和/或提示也被赞赏。猜测数字在时间限制内
import java.util.*;
import static java.lang.System.out;
import java.io.*;
public class Threading implements Runnable {
private static int num;
private static int k;
public void run() {
try {
Scanner line = new Scanner(System.in);
k = -1;
out.println("Guess!");
while (k != num) {
k = line.nextInt();
if (k != num) {
out.println("Nope");
}
}
}
catch (Exception e) {
out.println("I'm not done!");
}
}
public static void main(String args[]) throws InterruptedException {
num = (int) (Math.random() * 9 + 1);
out.println(num);
Thread t = new Thread(new Threading());
t.start();
long patience = 1000 * 5;
long startTime = System.currentTimeMillis();
while (t.isAlive()) {
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
out.println("I'm in here!");
t.interrupt();
t.join();
out.println("Times up!");
}
}
}
}
[如何中断java.util.Scanner nextLine调用](https://stackoverflow.com/questions/4983065/how-to-interrupt-java-util-scanner-nextline-call) –
@MarkMucha是否有必要使用Streams/Buffers来使代码正常工作?有没有办法结束'nextInt()'的“block”? – TypeHereToSearch