我有一個小程序可以做以下事情: 主線程和線程t1週期性地請求一個東西,一個按鈕將停止這兩個。從另一個線程調用timer.cancel()之後,TimerTask不會立即停止嗎?
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
我發現類似的問題here,回答說:電話從該時期內取消() ,但在這裏似乎不起作用。 那麼如何避免意外運行? t.cancel()
和this.cancel()
之間的區別是什麼?他們導致相同的結果。 謝謝!
它似乎取消工作正常,但。它取消,然後打印該行,因爲它應該。 – matt
至於你後來的問題。 'this.cancel()'取消TimerTask,這意味着Timer可以繼續工作。 t.cancel()取消定時器。 – matt
另外,我想阻止你使用applet。 – matt