3 Replies Latest reply on May 28, 2007 3:16 AM by 807606

    How to wait without using threads


      Is it possible in Java to tell the program to wait without using threads. I am making an applet and want something to be displayed after a few seconds and Threads are to complicated. Also I don't need Threads, because theres nothing to be done simultaneous.
        • 1. Re: How to wait without using threads
          You don't need to no much about Threads to use the Thread.sleep() method. It is pretty easy, you should however use a timer Object. If you want something easy then take a look at this:
          public class SleepTest {
               public static void main(String[] args) {
                    try {
                         Thread.sleep(5000); // sleep for five seconds
                         System.out.println("This prints in 5 seconds");
                    } catch (InterruptedException e) {
          You have to use a try-catch block because it can throw and InterruptedException.
          • 2. Re: How to wait without using threads
            another possibility
                    try {
                        TimeUnit.MINUTES.sleep(5);  // or TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException ignored) { }
            but it is almost the same as using Thread.sleep...
            and using import static
            import static java.util.concurrent.TimeUnit.MINUTES;
            // ...
                    try {
                    } catch (InterruptedException ignored) { }

            Message was edited by:

            but it's not a good idea to do that in the Thread responsible for painting (the AWT-Queue)
            • 3. Re: How to wait without using threads
              The easiest way to achieve that sort of effect in Swing is to use javax.swing.Timer.

              Try it. It really is easy: http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html