作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何制作一个会问 5 个问题(多项选择 a 到 d)的程序?
每个问题都有 30 秒的倒计时,使用线程 sleep (返回倒计时)当倒计时为 0 时,将进入下一个问题
以及如何使用公式添加分数?
import java.util.Scanner;
import java.io.IOException;
class timer{
public static void main(String[]args) throws IOException{
Scanner scan = new Scanner(System.in);
Thread thread1 = Thread.currentThread();
Thread thread2 = new Thread(() -> {
try{
for(int seconds = 30; seconds >= 0; seconds--){
System.out.println("\rYou have "+seconds+"second's left!");
Thread.sleep(1000);
}
}catch(InterruptedException e){}
});
System.out.println("What is 1+1? ");
System.out.println("a. 1\t b.2\t c.3\t d.4");
thread2.start();
String answer = scan.next();
thread2.stop();
}
}
最佳答案
我个人会使用 await
和 signal
/signalAll
同步我的线程,并依赖方法 Condition#await(long time, TimeUnit unit)
知道在等待时是否给出答案,所以我的代码将是这样的:
Scanner scan = new Scanner(System.in);
// The lock used to used to synchronize my threads
Lock lock = new ReentrantLock();
// The target condition
Condition answered = lock.newCondition();
Thread thread2 = new Thread(() -> {
try {
// Indicates whether the question has been answered
boolean hasAnswered = false;
lock.lock();
try {
// Loop until the question has been answered or 10 seconds
for (int seconds = 10; !hasAnswered && seconds >= 0; seconds--){
System.out.printf("You have %d sec's left!%n", seconds);
// Wait 1 second and if await returns true it means that
// I had an answer in time otherwise it means that we
// reached the timeout without getting answer
hasAnswered = answered.await(1L, TimeUnit.SECONDS);
}
} finally {
lock.unlock();
}
// Print the message indication whether we get the answer in time or not
if (hasAnswered) {
System.out.println("Good Job !!");
} else {
System.out.println("Too late !!");
}
} catch(InterruptedException e){
Thread.currentThread().interrupt();
}
});
System.out.println("What is 1+1? ");
System.out.println("a. 1\t b.2\t c.3\t d.4");
thread2.start();
String answer = scan.next();
lock.lock();
try {
// Notify the other thread that we have an answer
answered.signalAll(); // could be answered.signal() as we have only
// thread waiting to be notified but it is a
// better practice to use signalAll
} finally {
lock.unlock();
}
成功时的输出:
What is 1+1?
a. 1 b.2 c.3 d.4
You have 10 sec's left!
You have 9 sec's left!
You have 8 sec's left!
You have 7 sec's left!
2
Good Job !!
输出以防为时已晚:
What is 1+1?
a. 1 b.2 c.3 d.4
You have 10 sec's left!
You have 9 sec's left!
You have 8 sec's left!
You have 7 sec's left!
You have 6 sec's left!
You have 5 sec's left!
You have 4 sec's left!
You have 3 sec's left!
You have 2 sec's left!
You have 1 sec's left!
You have 0 sec's left!
Too late !!
关于Java——如何进行简单的考试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335957/
我是一名优秀的程序员,十分优秀!