ネコと和解せよ

いまさらJavaのTimerの挙動を調べる。

JavaのTimerをキャンセルしたときに、実行中のタスクがどうなるのか調べていなかったので調べた。

import java.util.Timer;
import java.util.TimerTask;

public class TimerTest {

    public static synchronized void print(String s){
        System.out.println(s);
    }
    public static void main(String[ ] args)
    {
        Timer timer=new Timer();
        timer.schedule(new TimerTask(){
            public void run(){
                print("timer task:in");
                try{
                    Thread.sleep(5000);
                }catch(Exception e){
                }
                print("timer task:out");
            }
        },0,100);
        print("timer started");
        try{
            Thread.sleep(1000);
        }catch(Exception e){
        }
        timer.cancel();
        print("timer canceled");
    }
}
timer started
timer task:in
timer canceled
timer task:out

cancelは実行中のタスクを待機しない。マジか。