我同意让线程休眠 1000 毫秒可能是最好的解决方案。您在尝试该解决方案时似乎遇到的问题可能是由于未使用多线程造成的。 Thread.sleep(1000); 命令应该位于与您用于用户界面的主线程不同的线程上。
以下可能是实现修改银行余额的线程的一种可能方式:
public class RevenueThread implements Runnable {
public void run() {
while(true){
// add to bank balance
MainClass.BankBalance += MainClass.PropertyCount * INCOME_PER_PROPERTY;
// sleep for 1 second
try{
Thread.sleep(1000);
}catch(Exception ex){
System.err.println( ex.getMessage() );
}
}
}
}
使用适当的变量名称等修改该代码以满足您的需要。
要将其与您的代码集成,您可以将其添加到您的 main() 函数中:
Runnable rev = new RevenueThread();
Thread revThread = new Thread(rev);
revThread.start();`
注意:如果我的回答显得有些简短或包含任何错误,我深表歉意。我正在用手机输入这个解决方案,所以请耐心等待:P
编辑:以下是每秒增加银行余额的另一种(也许更准确)方法:
public class RevenueThread implements Runnable {
public void run() {
// Variable to keep track of payout timing:
long lNextPayout = System.currentTimeMillis() + 1000; // Current time + 1 second
while(true){
if(lNextPayout <= System.currentTimeMillis()){
// At least 1000 milliseconds have passed since the last payout
// Add money to the player's bank balance
MainClass.BankBalance += MainClass.PropertyCount * INCOME_PER_PROPERTY;
// Now set up the next payout time:
lNextPayout += 1000;
}
// sleep for 50 milliseconds to prevent CPU exhaustion
try{
// Thread.sleep() can throw an InterruptedException.
Thread.sleep(50);
}catch(Exception ex){
// If sleep() is interrupted, we should catch the exception
// and print the error message to the standard error stream
// (STDERR) by using System.err
System.err.println( ex.getMessage() );
}
}
}
}
这个版本有什么不同,为什么更好?这个版本使用系统的当前时间每1000毫秒支付一次。因为sleep() 可能会抛出异常,所以这个更新版本可以防止用户在 1 秒内被多次支付,因为sleep() 抛出了异常并且整整一秒都没有休眠。
如何使用? 使用方式与之前的版本完全相同。 (即,只需创建一个新的RevenueThread 对象,然后为其创建一个Thread 对象,并在该新线程上调用.start()。)同样,您应该根据需要替换和重命名变量以适应您的项目.