简体   繁体   English

Java 定时器线程操作

[英]Java Timer Thread Operation

I am using Timer Thread to run a simple print function.我正在使用 Timer Thread 运行简单的打印 function。 The thing is that if I set my delay time is 1000ms, the program would just exit without any output.问题是,如果我将延迟时间设置为 1000 毫秒,程序将直接退出而没有任何 output。

But if I switch to 100ms, the program would be just fine.但如果我切换到 100 毫秒,程序就可以了。

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".根据JavaDocs ,使用默认构造函数创建Timer将创建一个用户线程,因此它“能够防止应用程序终止”。

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 timer = new Timer(true);

will show that the thread actually terminates immediately with the rest of the program when main() finishes:将显示线程实际上在main()完成时立即终止,并以程序的 rest 结束:

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.使用ideone尝试您的代码还可以验证程序在main()之后不会终止,而是继续执行直到 JVM 终止(有一个内置的 5 秒超时),然后打印预期的 output。

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. output 是否在预定时间或应用程序退出时打印,可能取决于底层操作系统和 JVM。

See this Waiting for a Timer to finish in Java .请参阅Java 中的等待计时器完成 Essentially, your main thread is completing before the Timer schedule occurs.本质上,您的主线程在 Timer 计划发生之前完成。

The schedule method will call your task with specified delay. schedule 方法将以指定的延迟调用您的任务。 1000 ms or 100 ms for your case.您的情况为 1000 毫秒或 100 毫秒。

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.您认为 100 毫秒延迟会很好的假设并不总是正确的。 There is possibility that your system will run the main thread faster than 100 ms and do not have time to run your task.您的系统可能会以超过 100 毫秒的速度运行主线程并且没有时间运行您的任务。 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 . @fedup 的链接建议ScheduledExecutorService

Another alternative would be to externally track task starts & stops with something like an Atomic<int> .另一种选择是使用Atomic<int>之类的外部跟踪任务开始和停止。 This could be error prone and lead to early program exits, or sleeping forever.这可能容易出错并导致程序提前退出或永远休眠。

I'd go with the scheduler.我会用调度程序 go 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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