简体   繁体   中英

Java Timer Thread Operation

I am using Timer Thread to run a simple print function. The thing is that if I set my delay time is 1000ms, the program would just exit without any output.

But if I switch to 100ms, the program would be just fine.

public class TimerTaskTest01 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new MyTask(), 1000);
    }
}
class MyTask extends TimerTask {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Hello World... ");
        }
        System.out.println("END");
    }
}

I think maybe the main thread is running too fast. But is there anyone can tell me that if I am right or not...

Actually, your application is probably still running (or should be), regardless of the scheduled timeout. According to the JavaDocs , creating a Timer using the default constructor will create a user thread , so it's "capable of keeping an application from terminating".

If you run the application with a debugger, you should see the timer thread being kept alive in the background as something like

Thread[Timer-0](Running)

Changing the Timer to use a daemon thread instead with

Timer timer = new Timer(true);

will show that the thread actually terminates immediately with the rest of the program when main() finishes:

terminated, exit value 0

Trying your code with ideone also verifies that the program doesn't terminate after main() , but instead continues execution until the JVM is terminated (there's a built-in five-second timeout), after which the expected output is printed.

Whether or not the output is printed at the scheduled time or when the application exits, is probably dependent on the underlying OS and JVM.

See this Waiting for a Timer to finish in Java . Essentially, your main thread is completing before the Timer schedule occurs.

The schedule method will call your task with specified delay. 1000 ms or 100 ms for your case.

From your code, the main thread will run that scheduler, then exit. Your assumption that 100 ms delay will be fine is not always true. There is possibility that your system will run the main thread faster than 100 ms and do not have time to run your task. This is what everybody called 'Race Condition'.

You start your task and then your program ends. You need to wait for the timer/tasks to complete before exiting your program:

public static void main(String[] args) {
    Timer timer = new Timer();
    int sleepTimeMS = 1000;
    timer.schedule(new MyTask(), sleepTimeMS);
    Thread.sleep(sleepTimeMS + 50); // just in case, an extra 50ms
}

The above solution is moderately terrible. A better way to do it would be to you some scheduler that allowed you to wait until all its tasks are complete. @fedup's link suggests ScheduledExecutorService .

Another alternative would be to externally track task starts & stops with something like an Atomic<int> . This could be error prone and lead to early program exits, or sleeping forever.

I'd go with the scheduler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM