Is it possible to create a separate background thread which would separately do some stuff?
I've tried the following program but it doesn't work as I expect.
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();
}
}
}
I expected that every 3 seconds "3 seconds passed" will be printed in the flow of multiple "--" strings.
In fact "3 seconds passed" is never printed. Why? And how can I create a background thread which would do something independantly from the main thread?
解决方案
Use java.util.TimerTask and java.util.Timer:
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
System.out.println("3 seconds passed");
}
},
0, // run first occurrence immediately
3000); // run every three seconds