定时器在Java中的使用



我正在为一家电影院编写一个订票系统。我想启动一个计时器,让用户在选择座位后有5分钟的时间结账。我决定使用java的Timer类。

这是启动计时器的代码,以及被调用的expiredCheckout()函数:

private void expiredCheckout() {
Scanner inputObj = new Scanner(System.in);
while (true) {
System.out.println("Your session has expired!");
System.out.println("If you want to start over, press 1"); 
System.out.println("If you want to cancel, press q");
String input = inputObj.next();
System.out.println("made it here");
if (input.equals("q"))
return;
else if (input.equals("1")) {
this.runTheatreUI();
break;
} else {
System.out.println("Please enter valid choice!");
}
}
}
private void startTimer(ArrayList<Seat> seatsSelected) {
Timer timer = new Timer();
timer.schedule(
new TimerTask() {
public void run() {
expiredCheckout();
return;
}
}
,5*60*1000);
ArrayList<Object> checkoutInfo = this.checkout();
timer.cancel();
if (checkoutInfo.get(0).equals(true)) {
for (int i = 0; i < seatsSelected.size(); i++) {
seatsSelected.get(i).setStatus(Seat.TAKEN);
this.numSeatsAvailable += 1;
}
} else {
// the user quit 
for (int i = 0; i < seatsSelected.size(); i++) {
seatsSelected.get(i).setStatus(Seat.OPEN);
this.numSeatsAvailable += 1;
}
}
return; 
}

正如您所看到的,我在阅读了用户的输入后添加了print语句。然而,该函数从未实现。当我在终端中输入字符时,没有任何操作。我很困惑为什么会发生这种事。

要取消计时器,您可以在TimerTask本身中执行此操作

private void expiredCheckout() {
System.out.println("in expired method");
Scanner inputObj = new Scanner(System.in);
while (true) {
System.out.println("Your session has expired!");
System.out.println("If you want to start over, press 1"); 
System.out.println("If you want to cancel, press q");
String input = inputObj.nextLine();
System.out.println("made it here");
if (input.equals("q")) {
System.out.println("quitting");
timer.cancel();
timer.purge();
return;
}
else if (input.equals("1")) {
System.out.println("Entered 1");
break;
} else {
System.out.println("Please enter valid choice!");
}
}                   
}

最新更新