是否可以创建一个单独的后台线程来执行一些任务?我尝试了下面的程序,但它没有按我的预期工作。
public class Test {
private static class UpdaterThread extends Thread {
private final int TIMEOUT = 3000;
public void run() {
while (true) {
try {
Thread.sleep(TIMEOUT);
System.out.println("3 seconds passed");
} catch (InterruptedException ex) {
}
}
}
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
try {
Thread u = new UpdaterThread();
u.start();
while (true) {
System.out.println("--");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我期望每3秒钟,“3秒已经过去”会在多个“--”字符串的流中打印出来。实际上,“3秒已经过去”从未被打印出来。为什么?如何创建一个独立于主线程的后台线程来执行某些操作?
Runnable
接口,详情请见这里。 - David Kroukampex.printStackTrace();
而不是留空catch块,这样比较无意义。 - David Kroukampcatch (InterruptedException e)
处理程序显然应该包含一个break;
-- 或者只需将while
放在 try 块内。 - Marko Topolnik