java在游戏中后台运行计数器线程
我想知道在玩游戏时,让计时器在后台运行的最佳方法
我正在编写HiLo游戏的一个版本(Java),它给用户一定的时间来确定一个数字。如果猜测不正确,游戏会告诉用户名字是太高还是太低
我用System.currentTimeMillis()
来记录时间,看看已经过去了多少时间。这似乎工作得很好,到目前为止,我一直在检查每次输入一个新数字时经过了多少时间。例如,当前应用程序输出如下所示:
Welcome to HiLo!
You have 10 seconds to guess a number I'm thinking of between 1 and 100.
> 67
Too high.
> 29
Too low.
Half of your time is gone! Only 5 seconds remains!
> 37
Too high.
> 33
Oops! Time is up - try again.
正如你所看到的,目前,它只能在我输入一个新数字时检查经过了多少时间
我曾尝试创建一个线程来启动计时器,但是,当我启动它时,它会一直计数,直到时间耗尽,而不会继续执行线程。运行(int guess),当有新的猜测时将运行该选项。我希望在计数器运行时仍能进行猜测。下面是我对线程的一个新实现的尝试。开始():
public void start(int time_sent) throws InterruptedException {
time = time_sent;
startTime = (System.currentTimeMillis() / 1000);
while (1==1) {
long elapsed = ((System.currentTimeMillis() / 1000) - (startTime));
if (elapsed >= (time)) {
System.out.println("Oops! Time is up - try again.");
System.exit(0);
}
else if (elapsed >= (time/2) && !halfWarning) {
System.out.println("Half of your time is gone! Only " + (time/2) + " seconds remains!");
halfWarning = true;
}
}
}
如何在后台继续运行此计数器
# 1 楼答案
这是另一种方法:
从1个线程开始,在后台类中实现行为。接下来,进入while循环以捕获用户输入。后台线程在后台工作
# 2 楼答案
它可能会激励你:
# 3 楼答案
你可以有一个Timer线程来打印这些消息并关闭监听程序