开发者

Java re-doing a piece of code ... using threads

Let's say I have this code:

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

           System.out.println("Hello World开发者_如何学C!");

        }
}

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


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();
    }
}


How about this?

public class helloworld
{
        public static void main(String args[])
        {
           while(true) {
               Thread.sleep(5000);
               System.out.println("Hello World!");
           }
        }
}


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);


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.


Using ScheduledExecutorService:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜