在Java中如何实现计时的这样一个功能,比如在限定时间完成游戏,没有完成就退出,怎么限定的时间呢?

如题所述

//可以启动一个线程来做时间计算
//也可以用timer来实现定时 timer使用wait 我这里用sleep
//关键不是用什么而是用线程来解决问题
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Runnable r = new Runnable() {
final long start = System.currentTimeMillis() ;
public void run() {
try {
while(true) {
Thread.sleep(1000);
long now = System.currentTimeMillis();
if(now-start>=10000) {
System.out.println("打字时间结束了");
System.exit(0);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
System.out.println("可以开始打字了,10秒后就不能打了");
Scanner s = new Scanner(System.in);
Thread t = new Thread(r);
t.start();
while(s.hasNext()) {
System.out.println(s.nextLine());
}
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-12-14
限定时间的话,可以使用Timer这个类,就是用来实现类似功能的。本回答被网友采纳
相似回答