Java重新编写一段代码…使用线程
假设我有这个代码:
public class helloworld { public static void main(String args[]) { System.out.println("Hello World!"); } }
使用线程,有没有办法让我的Hello世界每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(); } }
这个怎么样?
public class helloworld { public static void main(String args[]) { while(true) { Thread.sleep(5000); System.out.println("Hello World!"); } } }
查看
http://download.oracle.com/javase/tutorial/essential/concurrency/sleep.html
它正在做你想做的事。 基本上在while循环中进行打印,并在打印后执行
Thread.sleep(5000);
最简单的方法是
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包提供。
使用ScheduledExecutorService :
ScheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("Hello, world!"); } }, 0 /* initial delay */, 5, TimeUnit.SECONDS);