[英]Why thread.stop deprecated and timer.cancel is not?
What is the difference between stopping a java Thread and stopping an instance of Timer ? 停止java Thread和停止Timer实例有什么区别?
Why is timer.cancel thread safe or is it ? 为什么timer.cancel线程安全或者是它?
Cancelling a timer doesn't have any of the potentially destabilizing behaviour of aborting a thread. 取消计时器不具有中止线程的任何潜在的不稳定行为。 From the docs :
来自文档 :
Does not interfere with a currently executing task (if it exists).
不干扰当前正在执行的任务(如果存在)。
In other words, it's not going to try to stop a task which is already running, which could potentially end up with monitors not being released etc. It's just going to avoid running any more tasks. 换句话说,它不会试图阻止其已在运行的任务,这有可能与未在发布等监控者,它只是要避免运行任何更多的任务结束了。
Timer.cancel
only cancels timer tasks that have not yet been started. Timer.cancel
仅取消尚未启动的计时器任务。 The Thread.stop
method stops the thread (by throwing an Error
) and may leave the system in an inconsistent state, since the thread is stopped in an unknown place, possibly while doing something. Thread.stop
方法停止线程(通过抛出Error
)并且可能使系统处于不一致状态,因为线程在未知位置停止,可能在执行某些操作时。
Java's Timer
implementation uses a loop and a flag to indicate whether its underlying Thread
should continue processing timer events. Java的
Timer
实现使用循环和标志来指示其底层Thread
是否应该继续处理计时器事件。 When you call cancel()
, the newTasksMayBeScheduled
flag is set to false, which clears any pending events, and causes the thread's loop to stop (allowing its run()
method to return). 当你调用
cancel()
, newTasksMayBeScheduled
标志被设置为false,它清除所有挂起的事件,并导致线程的循环停止(允许其run()
方法返回)。 In other words, it does not use the unsafe Thread#stop()
method. 换句话说,它不使用不安全的
Thread#stop()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.