1

I want to add a delay in my program using the Thread.sleep(1000) command (so making it stop for 1 second before continuing) but this means I also need to add the throws InterruptedException. However, I'm not sure where to put it.

My code basically looks like this right now:

public static void main(String[] args) {
    Clock myClock = new Clock;   // new clock object.

    while (true) {
        myClock.tick();
    }
}

My other class:

public class Clock {
    // .. some constructors and stuff

    public void tick() {
        secondHand.draw();   // redraws the second hand to update every second
    }

    // .. some more methods and stuff
}

I want to only call the tick() method every 1 second, but I don't know where I can put the Thread.sleep and throws InterruptedException statements. Any help would be appreciated. Also any input on other ways I can make my clock tick and/or update would be helpful too!

yiwei
  • 4,022
  • 9
  • 36
  • 54
  • If you're running in a graphics environment like Swing, use a [`javax.swing.Timer`](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) as I demonstrated in your previous question [How can I make a clock tick?](http://stackoverflow.com/questions/13116414/how-can-i-make-a-clock-tick/13116623#13116623) – MadProgrammer Oct 30 '12 at 03:33
  • @MadProgrammer you're just helping me out with all kinds of issues today! Thanks! I'm working with a StdDraw library from the StdLib.jar file found [here](http://introcs.cs.princeton.edu/java/stdlib/) (I am but a lowly college CS student) – yiwei Oct 30 '12 at 03:36
  • By the way, if you pause for a clock it will slightly delay because you are not counting cpu spent time in previous code. – PbxMan Oct 30 '12 at 03:42
  • @59eagle We're all students ;). Be careful though, you are still running with the Swing environment, any long running or block processes will cause you program to look like it's hung/crashed. If you want to use something like `Thread.sleep` you are better of using a separate thread. This means you become responsible for re-sync any updates to the UI back into the [Event Dispatching Thread](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html). I just don't want your next question to be, "Why does my program hang?" ;) – MadProgrammer Oct 30 '12 at 03:52

5 Answers5

5

I want to only call the tick() method every 1 second

After the call to tick(), put a sleep on the current thread as follows:

public static void main(String[] args) {
    Clock myClock = new Clock;   // new clock object.

    while (true) {
        myClock.tick();
        // wait for a second.
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException ie) {
            // Handle the exception
        }
    }
}
Vikdor
  • 23,934
  • 10
  • 61
  • 84
1

Depending on the flow of your program you will want to put the Thread.sleep(1000); statement into your controlling logic. By this I mean that whatever logic calls your tick() method would by convention be the best place to introduce your logic control - in this case your Thread.sleep(1000); statement.

Alas your calling logic should look something like this:

try {
    while (true) {
        Thread.sleep(1000);
        myClock.tick();
    }
} catch(InterruptedException e) {
    System.err.println("Something went wrong");
}

This approach ensures that if you have other controlling logic accessing your tick() method then it won't be tied into the 1 second delay. Different clients usually have different needs...

I prefer to wrap the entire while loop in the try catch block for scalability safe readability... By this I mean the if the logic in you tick() method gets more complex and you end up throwing more exceptions then you can simply add the catch clause to the one try catch block like so:

try {
    while (true) {
        Thread.sleep(1000);
        myClock.tick();
    }
} catch(InterruptedException e) {
    System.err.println("Something went wrong");
} catch(SomeNewExcetion e) {
    System.err.println("Something went wrong");
} catch(SomeOtherNewExceptoion e) {
    System.err.println("Something went wrong");
} catch(SomeFinalException e) {
    System.err.println("Something went wrong");
}
travega
  • 8,284
  • 16
  • 63
  • 91
  • 2
    (I'm nit picking) But would you be able to explain the differences between you example and Vikdor's (it's not wrong, but a little more explanation might help the OP ;)) – MadProgrammer Oct 30 '12 at 03:46
  • That's a fair point, but I would suggest that the main reason for wrapping the loop inside the exception handler is so that you don't end up with a run away loop, that, if for some reason, something goes bad, the loop will be automatically exited ;) - IMHO – MadProgrammer Oct 30 '12 at 04:02
1

You could use either javax.swing.Timer or java.util.Timer to achieve the same results.

The javax.swing.Timer has the advantage of when it's triggered, the ActionPerformed method is executed within the Event Dispatching Thread, making updates to the UI easier.

java.util.Timer

timer = new Timer();
timer.schedule(new TickTock (), 1000);

public class TickTock extends TimerTask {
    public void run() {
        System.out.println("Tick tock!");
    }
}

javax.swing.Timer

Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Tick tock!");
        repaint();
    }
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();

You can have read through How to Use Swing Timers for more info on javax.swing.Timer

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

Although I would not normally suggest it.

In this case you do not really need to code for this being interrupted. Hide it by wrapping with a runtime exception.

public class Clock {
    // .. some constructors and stuff

    public void tick() {
       secondHand.draw();   // redraws the second hand to update every second
    }
    public void wait() {
       try {
           Thread.sleep(1000)
       } catch(InterruptedException e) {
           throw new RuntimeException("Don't know how to handle this", e);
       }
    }
   // .. some more methods and stuff
}
Tinman
  • 786
  • 6
  • 18
0

its Very Simple in java

TimeUnit.SECONDS.sleep(2);