1

Let's say I have this code:

public class helloworld
{
        public static void main(String args[])
        {

           System.out.println("Hello World!");

        }
}

Using threads, is there a way I can make Hello world echo continuously every 5 seconds?

0

5 Answers 5

5

This version repeats the hello world message continuously, while allowing the user to terminate the message-writing thread:

public class HelloWorld {

    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(new Runnable() {

            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        Thread.sleep(5000);
                        System.out.println("Hello World!");
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        thread.start();
        System.out.println("press any key to quit");
        System.in.read();
        thread.interrupt();
    }
}
2

How about this?

public class helloworld
{
        public static void main(String args[])
        {
           while(true) {
               Thread.sleep(5000);
               System.out.println("Hello World!");
           }
        }
}
1
  • 1
    Don't you need to catch InterruptedExceptions that might be thrown by Thread.sleep()? Feb 23, 2011 at 21:32
1

check out

http://download.oracle.com/javase/tutorial/essential/concurrency/sleep.html

it is doing what you want to do. basically do the print in a while loop, and after the print do a

Thread.sleep(5000);
0

Easiest way would be

Runnable r = new Runnable(){
public void run(){
  while(somecondition){
    Thread.sleep(5000); // need to catch exceptions
    helloworld.main(null);
   }
}

new Thread(r).start();

But you should probably use the Timer and TimerTask classes instead available through the java.concurrency package.

0

Using ScheduledExecutorService:

ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  @Override public void run() {
    System.out.println("Hello, world!");
  }
}, 0 /* initial delay */, 5, TimeUnit.SECONDS);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.