Java正在做一段代码。。。使用线程
假设我有以下代码:Java正在做一段代码。。。使用线程,java,multithreading,Java,Multithreading,假设我有以下代码: public class helloworld { public static void main(String args[]) { System.out.println("Hello World!"); } } 使用线程,有没有一种方法可以让Hello world每5秒连续回音一次?这个怎么样 public class helloworld { public static void
public class helloworld
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
使用线程,有没有一种方法可以让Hello world每5秒连续回音一次?这个怎么样
public class helloworld
{
public static void main(String args[])
{
while(true) {
Thread.sleep(5000);
System.out.println("Hello World!");
}
}
}
这个怎么样
public class helloworld
{
public static void main(String args[])
{
while(true) {
Thread.sleep(5000);
System.out.println("Hello World!");
}
}
}
退房
它是做你想做的事。基本上是在一个while循环中进行打印,然后在打印之后执行一个while循环
Thread.sleep(5000);
退房
它是做你想做的事。基本上是在一个while循环中进行打印,然后在打印之后执行一个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();
但是您可能应该使用java.concurrency包中提供的和TimerTask类 最简单的方法是
Runnable r = new Runnable(){
public void run(){
while(somecondition){
Thread.sleep(5000); // need to catch exceptions
helloworld.main(null);
}
}
new Thread(r).start();
但是您可能应该使用java.concurrency包中提供的和TimerTask类 此版本连续重复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();
}
}
此版本连续重复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();
}
}
使用:
使用:
你不需要捕捉到可能由
Thread.sleep()
引发的InterruptedException
吗?你不需要捕捉到可能由Thread.sleep()
引发的InterruptedException
吗?为什么我们有投票来解决这个问题?为什么我们有投票来解决这个问题?