public static void main(String[] args) throws InterruptedException {
final long thresholdTime = 11 * 1000;//in seconds
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Game Over. Couldn't cancel the time bomb.... Booommm.");
System.exit(0);
}
}, thresholdTime);
// Normall processing of program...
//TimeUnit.SECONDS.sleep(10);
// When you think you are good with your inputs.. call this
timer.cancel();
}
# 1 楼答案
使用一个Timer类并向其中添加一个Timer schedule任务,该任务的作用类似于退出进程。定时器启动后,退出程序