3 Replies Latest reply: May 27, 2007 10:16 PM by 807606 RSS

    How to wait without using threads

    807606
      Hi

      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
          807606
          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) {
                         e.printStackTrace();
                    } 
               }
          }
          You have to use a try-catch block because it can throw and InterruptedException.
          • 2. Re: How to wait without using threads
            807606
            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 {
                        MINUTES.sleep(5);
                    } catch (InterruptedException ignored) { }
            []

            Message was edited by:
            S_i_m_u

            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
              807606
              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