如何暂停我的 Java 程序 2 秒钟 [英] How to pause my Java program for 2 seconds
本文介绍了如何暂停我的 Java 程序 2 秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 新手,正在制作一个用于练习的小游戏.
I'm new to Java and making a small game for practice.
if (doAllFaceUpCardsMatch == false) {
//run pause here//
concentration.flipAllCardsFaceDown();
} else {
concentration.makeAllFaceUpCardsInvisible();
}
我想在此之前暂停游戏两秒钟
I want to pause the game for two seconds here before it does
concentration.flipAllCardsFaceDown();
我将如何暂停它?
推荐答案
您可以使用:
Thread.sleep(2000);
或
java.util.concurrent.TimeUnit.SECONDS.sleep(2);
请注意,这两个方法都会抛出InterruptedException
,这是一个已检查的异常,因此您必须捕获它或在方法中声明.
Please note that both of these methods throw InterruptedException
, which is a checked Exception, So you will have to catch that or declare in the method.
捕获异常后,您的代码将如下所示:
After Catching the exception, your code will look like this:
if (doAllFaceUpCardsMatch == false) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
concentration.flipAllCardsFaceDown();
} else {
concentration.makeAllFaceUpCardsInvisible();
}
由于您是新手,我建议您在熟悉 Java 后学习如何进行异常处理.
Since you are new, I would recommend learning how to do exception handling once you are little bit comfortable with java.
这篇关于如何暂停我的 Java 程序 2 秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文