- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试为一个简单的数学测验制作一个计时器,用户需要在 10 秒内回答问题,当时间超过时,它将加载到下一个问题。我找到了实现 Executorservice 和 future 的解决方案,但是当用户输入整数以外的其他输入时,它不断重复无效输入循环(数字格式异常),我遇到了问题> 在我的游戏课上。
希望了解以下内容有用:MathQuestion 类(生成数学问题的地方)、Game(启动游戏回合)和 GameTimer 类。
游戏类:-
//for 10 rounds of game
for (int i=0; i<rounds; ++i)
{
System.out.println("*************************************");
System.out.println("\nRound " + (i+1)
+ "\nEnter 'x' to quit game");
System.out.println("\nQuestion:");
//call method to generate question and get correct answer
result = quiz.Questions();
System.out.println("You have 10 seconds");
//to make sure we read a line or interrupt it for the timer
ExecutorService ex = Executors.newSingleThreadExecutor();
try
{
//retrieve the actual result at a later point in time.
Future<String> ans = ex.submit(new GameTimer());
try {
boolean validInput = false;
do
{
System.out.println("\nEnter your answer: ");//prompt user input answer
//10 secs wait to obtain result from player
//wait until callable complete before return result
answer = ans.get(10, TimeUnit.SECONDS);
//answer = scan.nextLine();
try
{
//valid player input
pAnswer = Double.parseDouble(answer.trim()) ; //convert to double
validInput = true;
}catch (NumberFormatException e){ //other input other than integers *this the repeated loop
System.out.println("Invalid input. Please try again.");
validInput = false;
ans = ex.submit(new GameTimer()); //resubmit task solution
}
if (answer.trim().equalsIgnoreCase("x")) //player quit game
{
quit=true;
break;
}
}while (!validInput);
if (quit)
{
break;
}
//for correct answer
if (Math.abs(Double.parseDouble(answer) - quiz.answer) <= 0.01) {
//add 10 points
this.gamer.setScore(score+=10);
System.out.println("You got it right!");
}
else //wrong answwer
{
//subtract 10 points
this.gamer.setScore(score-=10);;
System.out.println("You got it wrong!");
}
} catch (InterruptedException ex1) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex1);
} catch (ExecutionException ex1) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex1);
} catch (TimeoutException ex1) {
System.out.println ("\nTime's up! Better luck next time~");
}
}finally {
ex.shutdownNow(); //stop all running tasks and shut the executor down immediately.
}
}
GameTimer 类:-
public class GameTimer implements Callable<String> {
public String call() throws IOException {
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
String input = "";
while ("".equals(input)) {
try {
while (!inp.ready()) {
Thread.sleep(1000);
}
input = inp.readLine();
} catch (InterruptedException e) {
return null;
}
}
return input;
}
}
这是输出循环问题的图片:loop problem
我已经尝试寻找计时器的解决方案很长一段时间了,如果有人可以提供帮助,我将非常感激。非常感谢。
*附加:有没有办法显示计时器倒计时(例如:10 9 8..),但当新的秒计数出现时删除前一秒?
(不删除建议也有帮助,谢谢!)
最佳答案
你不能一直重新调用get。您的任务是可执行文件,您提交它然后它就会运行。你调用 .get ,它就会得到你的执行结果。您需要重新提交任务,例如:
catch (NumberFormatException e){ //other input other than integers *this the repeated loop
System.out.println("Invalid input. Please try again.");
validInput = false;
ans = ex.submit(new GameTimer());
}
您可能想要跟踪自每次调用 get 时使用相同的超时以来所耗时。
在我看来,您应该将错误处理放在可调用中。
final String question = "Enter double value";
Callable<Double> getDouble = ()-{
BufferedReader inp = new BufferedReader(neww InputStreamReader(System.in));
while (!Thread.currentThread().isInterupted()) {
System.out.println(question);
try {
String input = inp.readLine();
Double v = Double.parseDouble(v);
return v;
} catch(Exception e){
if( Thread.currentThread().isInterrupted()){
return null;
}
System.out.println("Invalid Input, try again");
}
}
}
现在,当您提交任务时,您不必担心无效的 double 值,因为它是在可调用任务中处理的。
Future<Double> ans = ex.submit(getDouble);
Double v = ans.get(10, TimeUnit.SECONDS);
这会留下一个问题:任务即使被取消,仍然会等待标准输入。解决此问题的最简单方法是告诉用户按 Enter 键继续。
关于Java:使用Executorservice和future作为计时器时如何打破循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60942194/
我有一个executorService,它不等待executorService部分完成,它直接返回返回值而不等待下面是我的代码:请查看我是否正确实现了executorService,并在需要时帮助我纠
我有一个运行在另一个执行器服务中的执行器服务来发送电子邮件。如果我在外部执行程序上调用关闭,它正在等待内部执行程序服务关闭,这会极大地影响响应时间。 private final ExecutorSer
我有两个 ExecutorService 实例:一个有 4 个线程,另一个有 20 个线程。我希望单击按钮后,服务 1 就会停止并等待服务 2 结束。之后,服务1继续运行。 我尝试使用 wait 和
我目前有一个 ExecutorService,我想要以下内容: 不应接受任何新任务。 当前任务仍应继续执行。 应返回所有当前排队的任务。 我面临的问题是 shutdown() 不会返回任何未执行的已提
/** * Blocks until all tasks have completed execution after a shutdown * request, or the timeout o
我在线程 A 上创建 ExecutorService,然后线程 B 在 ExecutorService 上调用 shutdown() 和 awaitTermination()。 假设在线程B创建之前所
为了提高请求的响应时间,我打算使用 executorService 并将工作分配给多个线程,以减少请求的响应时间。 但是在阅读文章和博客后,为每个请求创建新的线程池也会影响性能。 闲置方法是什么,-1
我正在学习使用 ExectorService 来汇集 threads 并发送任务。我下面有一个简单的程序 import java.util.concurrent.ExecutorService; im
这是我为暴露我的问题所做的一个简化示例。我有任务doSomeWork()我使用 ExecutorService(一次最多 4 个线程)以多线程方式处理。但是,如果任何线程/任务产生异常,我想: 停止处
我的类路径中有 Guava ,想使用 ListenableFuture s,但目前我不知道如何提交ListenableFuture s 还是目前只能在调用线程中没有执行程序的情况下使用它们?我读过 r
我正在学习 ExecutorService 和 Callables,但收到来自 intelij 的警告,说我正在为此行进行未经检查的分配: Future> future = executorServi
我正在编写一个 Java Fractal Explorer,分形计算是多线程完成的。以前,我只是创建了一堆线程(与系统有处理器内核一样多)并将它们保存在一个数组中,但这会导致一些问题并且不是很优雅,现
我想加入两个在 ExecutorService 中执行的线程。 public class CURD { public static ExecutorService executorService
我有一个工作单元列表,我想并行处理它们。每个单元工作 8-15 秒,完全计算时间,没有 I/O 阻塞。我想要实现的是拥有一个 ExecutorService那: 当没有工作要做时,实例化的线程为零 如
我想同时向最多 10 个用户发送 ping,并在 ping 完成后用结果更新用户对象。 为了做到这一点,我尝试使用 ExecutorService . 我从这样的代码开始: private void
我有一个在 ForkJoinPool 线程池中执行的递归批量任务。 public class SomeTask extends RecursiveAction { @Override
我有一个要遍历的列表,并且对于列表中的每个值都将调用一个方法。现在我已经将相关方法放在一个线程中,并使用执行器服务来并行处理这些方法。但是,对于列表中的每个值,该方法最终会由于某种原因被调用两次。 E
这个问题已经有答案了: How to wait for all threads to finish, using ExecutorService? (27 个回答) 已关闭 4 年前。 我正在尝试使用
我有一个基于ExecutorService线程流量调节的问题:我想 .submit() 多个线程来执行,我希望一些线程等待,直到特定的先前线程完成执行。 。 到目前为止,我知道一种通过使用 Count
我想知道这段代码是否正确。当我在构造对象本身时将可运行对象提交给执行器服务时,这不会导致问题吗? public class A implements Runnable { public
我是一名优秀的程序员,十分优秀!