【发布时间】:2020-05-14 21:41:08
【问题描述】:
我正在尝试使用此功能构建命令行界面:如果用户插入输入(在本例中为整数)花费的时间超过 15 秒,则该函数会做出默认选择 (0)。下面的代码是我到目前为止写的,它工作正常。
问题是我想添加一个新功能:如果用户输入了错误的数字(range),控制台应该打印类似("Wrong choice, you have to pick an integer between 0 - "+ range);
但是,当控制台打印消息时,计时器应该仍在运行并在 15 秒后结束此循环,以防用户不断插入错误的数字。如果用户最终得到一个正确的数字,它应该立即中断循环。
这是我的代码,但我对如何添加功能没有明确的想法,因为我对 Future、Callable 和 Executor 功能比较陌生。如果有人对此有更多经验,我很乐意学习!
private int getChoiceWithTimeout(int range){
Callable<Integer> k = () -> new Scanner(System.in).nextInt();
Long start= System.currentTimeMillis();
int choice=0;
ExecutorService l = Executors.newFixedThreadPool(1); ;
Future<Integer> g;
System.out.println("Enter your choice in 15 seconds :");
g= l.submit(k);
while(System.currentTimeMillis()-start<15*1000 && !g.isDone()){
// Wait for future
}
if(g.isDone()){
try {
choice=g.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
g.cancel(true);
return choice;
}
【问题讨论】:
标签: java timeout java.util.scanner future callable