从另一个线程调用 timer.cancel() 后,TimerTask 不会立即停止吗?
TimerTask doesn't stop immediately after timer.cancel() being called from another thread?
我有一个小程序可以做以下事情:
主线程和线程 t1 循环请求一些东西,一个按钮将停止两者。
public class HttpsConn {
private static boolean stop = false;
private static Timer t = null;
public static void main(String[] arg) {
t = new Timer();
A a = new A();
t.schedule(a, 0, 1000);
B b = new B();
Thread t1 = new Thread(b);
t1.start();
}
static class A extends TimerTask {
@Override
public void run() {
if (stop)
t.cancel(); //this.cancel();
System.out.println("something to do");
}
}
static class B extends A implements Runnable {
@Override
public void run() {
System.out.println("simulate an operation from Swing Applet (click RESET button) to interrupt the thread.");
stop = true;
}
}
}
我除了结果:
something to do
simulate an operation from Swing Applet (click RESET button) to interrupt the thread.
我得到的:
something to do
simulate an operation from Swing Applet (click RESET button) to interrupt the thread.
something to do
我发现了一个类似的问题 ,答案是 call cancel from within the 运行(),但它似乎在这里不起作用。
那如何避免意外的运行ning呢?
t.cancel()
和 this.cancel()
有什么区别?它们导致相同的结果。
谢谢!
您的 A
计划 运行,初始延迟为 0
,后续延迟为 1
秒。
第一个 something to do
是在 0
延迟后第一次执行。 stop
标志尚未设置,因此它只是打印并退出。
一秒钟后,Timer
再次调用它。它检查 stop
标志,取消计时器(因为 B
已执行并设置它)并打印第二个 something to do
。它不应该再次 运行,因为计时器任务现在已被取消。
为了避免这种看似奇怪的行为,您可以使用类似的东西:
if (!stop) {
System.out.println("something to do");
} else {
t.cancel(); //this.cancel();
}
请记住,cancel
仅取消 Timer
,它不会中止 Runnable
.
的执行
我有一个小程序可以做以下事情: 主线程和线程 t1 循环请求一些东西,一个按钮将停止两者。
public class HttpsConn {
private static boolean stop = false;
private static Timer t = null;
public static void main(String[] arg) {
t = new Timer();
A a = new A();
t.schedule(a, 0, 1000);
B b = new B();
Thread t1 = new Thread(b);
t1.start();
}
static class A extends TimerTask {
@Override
public void run() {
if (stop)
t.cancel(); //this.cancel();
System.out.println("something to do");
}
}
static class B extends A implements Runnable {
@Override
public void run() {
System.out.println("simulate an operation from Swing Applet (click RESET button) to interrupt the thread.");
stop = true;
}
}
}
我除了结果:
something to do
simulate an operation from Swing Applet (click RESET button) to interrupt the thread.
我得到的:
something to do
simulate an operation from Swing Applet (click RESET button) to interrupt the thread.
something to do
我发现了一个类似的问题 t.cancel()
和 this.cancel()
有什么区别?它们导致相同的结果。
谢谢!
您的 A
计划 运行,初始延迟为 0
,后续延迟为 1
秒。
第一个 something to do
是在 0
延迟后第一次执行。 stop
标志尚未设置,因此它只是打印并退出。
一秒钟后,Timer
再次调用它。它检查 stop
标志,取消计时器(因为 B
已执行并设置它)并打印第二个 something to do
。它不应该再次 运行,因为计时器任务现在已被取消。
为了避免这种看似奇怪的行为,您可以使用类似的东西:
if (!stop) {
System.out.println("something to do");
} else {
t.cancel(); //this.cancel();
}
请记住,cancel
仅取消 Timer
,它不会中止 Runnable
.