1

我有一个游戏,包括随着游戏进行的计时,我的意思是你玩游戏和时间滴答,当它完成时它会停止游戏。但我不能一次运行两个代码线程......有什么办法可以解决这个问题吗?

这是我的计时器代码:

public class Time {
private static String gl;
private static int gli;
public static int weeks = 0;

public static void main(String[] args) throws InterruptedException {
    startdays();
}
public static void startdays() throws InterruptedException {
    gl = JOptionPane.showInputDialog("How many weeks? do you want the game to to on for?\nPlease type numbers, Or game will crash.\nEach week is 10 seconds long.");
    gli = Integer.parseInt(gl);
    gli++;

    for (int i = 0; i < gli; i++) {         
        if(weeks < gli){
            Thread.sleep(10000);
            weeks++;
        }else if(weeks == gli){
            JOptionPane.showMessageDialog(null, "Uh oh, Your time in office is up. You died of an infectuous disease.");                
        }
    }
}
}

在另一个类中,我这样调用该方法

JOptionPane.showMessageDialog(frame, compname);
    Time time = new Time();
    time.startdays();
    JOptionPane.showMessageDialog(frame, "Im still here");

那么有没有办法让计时器和游戏同时进行呢?

4

1 回答 1

0

如果您正在运行 Swing,那么您已经在运行多个线程,因为 Swing 在它自己的线程中运行。

首先看一下Swing 中的并发

特别是,javax.swing.Timer这很可能是对您最有用的选项

更新

可能的例子

于 2013-07-12T23:56:31.303 回答