Java重新编写一段代码...使用线程 [英] Java re-doing a piece of code ... using threads
本文介绍了Java重新编写一段代码...使用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这段代码:
public class helloworld
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
使用线程,有没有办法我可以每隔5秒连续让Hello世界回声吗?
Using threads, is there a way I can make Hello world echo continuously every 5 seconds?
推荐答案
这个版本连续重复hello world消息,同时允许用户终止消息编写线程:
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();
}
}
这篇关于Java重新编写一段代码...使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文