我正在尝试制作一款只能输入 10 秒单词的游戏。我尝试创建一个多线程解决方案,但它无法正常工作。
class timer extends Thread{//thread
public void run(){
for(int i=10;i>=0;i--){
System.out.print(i+" ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
主要方法:
timer t=new timer();
t.start();
while () {//not sure what to put in my while statement
System.out.print("Guess a word on the board! ");
if(test.CheckGame(scan.next())==true){
System.out.print("Good job! ");
}
else
System.out.print("Guess again! ");
}
本质上,在线程运行 10 秒并终止后,我希望它返回一个 Break 语句,以便程序离开 while 循环。有什么建议么?
最佳答案
将您的代码更改为此
timer t=new timer();
t.start();
while (t.isAlive()) {//not sure what to put in my while statement
System.out.print("Guess a word on the board! ");
if(test.CheckGame(scan.next())==true){
System.out.print("Good job! ");
}
else
System.out.print("Guess again! ");
}
一旦 run 函数退出,t.isAlive 将为 false。您可能还需要传递计时器对象并检查该对象的 isAlive(),具体取决于 CheckGame 的工作方式。这样,输入就无法在 10 秒后无限期地输入。
关于java - 尝试对计时器进行编程,以便用户只能在一定时间内输入单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15732362/