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?
Runnable
, see here – Gomesex.printStackTrace();
never leave catch blocks empty, its rather pointless than – Gomescatch (InterruptedException e)
handler should obviously contain abreak;
-- or just putwhile
inside the try-block. – Woosley