Java重新编写一段代码...使用线程

时间:2011-02-23 21:28:25

标签: java multithreading

假设我有这段代码:

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

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

        }
}

使用线程,有没有办法让我的Hello世界每隔5秒连续回声一次?

5 个答案:

答案 0 :(得分:5)

此版本不断重复hello world消息,同时允许用户终止消息编写线程:

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

答案 1 :(得分:2)

这个怎么样?

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

答案 2 :(得分:1)

结帐

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

它正在做你想做的事。基本上在while循环中进行打印,并在打印后执行

Thread.sleep(5000);

答案 3 :(得分:0)

最简单的方法是

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

new Thread(r).start();

但您应该使用Timer和TimerTask类,而不是通过java.concurrency包提供。

答案 4 :(得分:0)

使用ScheduledExecutorService

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