gpt4 book ai didi

java - 丢失线程时出现异常

转载 作者:行者123 更新时间:2023-12-02 08:36:04 26 4
gpt4 key购买 nike

我使用 Timer 和 TimerTasks 启动两个线程

Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
doSomething();
}
};
Calendar start = Calendar.getInstance();
timer.scheduleAtFixedRate(task, start.getTime(),
1000 * 60 * 60);

现在有时第二个线程会停止。当该线程停止时,是否有可能观察该线程,也许是为了发送邮件,也许是通过寻找第二个线程的第三个线程?

最佳答案

您需要保持对 Timer 的引用处于 Activity 状态 - 如果 Timer 被垃圾回收,线程将停止。来自 the docs :

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the timer's cancel method.

可能不是问题所在,但它是最可能的原因。我想如果你能让线程保持 Activity 状态,你就不需要任何检查?

关于java - 丢失线程时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1761921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com