1

I have a game that includes timing as the game progresses, i mean you play the game and time ticks as you play, and when its done it stops the game. But i can't run two threads of code at once... is there any way i could fix this?

here is my timers code:

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.");                
        }
    }
}
}

In another class I call the method like so

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

So is there any way to have the timer and the game going at the same time?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) A single blank line of white space in source code is *always* enough. – Andrew Thompson Jul 13 '13 at 04:36

1 Answers1

0

If you are running Swing, you are already running multiple threads, as Swing runs in it's own thread.

Start by taking a look at Concurrency in Swing.

In particular, javax.swing.Timer is most likely the most useful option to you

Updated

Possible examples

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366