Java re-doing a piece of code … using threads

2020-02-15 06:14发布

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?

5条回答
▲ chillily
2楼-- · 2020-02-15 06:35

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);
查看更多
看我几分像从前
3楼-- · 2020-02-15 06:35

Using ScheduledExecutorService:

ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  @Override public void run() {
    System.out.println("Hello, world!");
  }
}, 0 /* initial delay */, 5, TimeUnit.SECONDS);
查看更多
甜甜的少女心
4楼-- · 2020-02-15 06:37

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();
    }
}
查看更多
【Aperson】
5楼-- · 2020-02-15 06:47

How about this?

public class helloworld
{
        public static void main(String args[])
        {
           while(true) {
               Thread.sleep(5000);
               System.out.println("Hello World!");
           }
        }
}
查看更多
小情绪 Triste *
6楼-- · 2020-02-15 06:48

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.

查看更多
登录 后发表回答