如何在时间后终止方法

How to terminate method after time

我正在尝试做一个订票系统。 客户可以 select 的方法之一是 makeOrder()。在这种方法中他 select 的票数然后我想给他 10 分钟到 select 座位。如果他 select 他们并确认订单,则该方法应该结束,他可以再次从 MainMenu select 选项。如果他在 10 分钟内没有 select 个座位,我想删除订单,通知他并给他看 MainMenu。我不知道该怎么做。谁能帮帮我。

pseudocode

public class MainMenu{

public void handle(String option) {  
   switch (option) {
      case "1":   showScreenings(); break;
      case "2":   makeOrder(); break;
      default:    System.out.println("Unknown option"); break;
   }
}

private void makeOrder(){
   // customer selects number of tickets and then order is created
   Order order = new Order()
   
   // here I want to give a customer 10 minutes to select seats so I tried it with Timer
   // but it deletes the order but still waiting for the input of the customer
   Timer t = new java.util.Timer();
    t.schedule( new java.util.TimerTask() {
        @Override
        public void run() {
            if (order.getOrderedDateTime() == null){
                try {
                    order.delete();
                    System.out.println("Time out");

                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            t.cancel();
        }
    }, TimeUnit.MINUTES.toMillis(10));

     //code to select seats
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     String seats = br.readline()  // if he doesnt select seats in 10 minutes I want to delete order
     
     //reserve seats and confirm order
     order.confirm();
}
}

我认为你的意思是“但仍在等待客户的输入”,你需要某种 UI 反馈,所以你可以通过多种方式处理这个问题,一种方式是你可以展示通知用户取消订单的对话框,并使用以下方式刷新 activity(如果可能):

finish();
startActivity(getIntent());

据我了解,您需要等待 10 分钟以等待用户操作。如果 10 分钟内 he/she 次操作,则您继续确认订单。

如果用户未能在 10 分钟内采取行动您要删除订单。

您可以尝试在特定时间等待线程完成的 Future。

System.out.println("Wait 10 seconds to get user input");
        
        StringBuilder stringBuilder = new StringBuilder();
        ExecutorService executor = Executors.newSingleThreadExecutor();
        
        Future<?> future = executor.submit(()->{
            //code to select seats
            System.out.println("Enter Seat No: ");
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             try {
                 stringBuilder.append(br.readLine()); 
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        
        try {
            future.get(10, TimeUnit.SECONDS);
            System.out.println("Seat selected. Let's confirm the order");
        } catch (TimeoutException | ExecutionException e) {
            future.cancel(true);
            System.out.println("Time out Delete oder");
            // delete order
        }  finally {
            executor.shutdownNow();
        }