1

问题陈述:我有一个类,里面有一个计时器。

class DeleteTimer {

    private Timer timer = new Timer();

    private static Timer timerStatic;

    public DeleteTimer(Member uid, String serverFilePath, String deleteTime) {

    }

    public static void start() {
        timerStatic.schedule(new TimerTask() {
            public void run() {
                deleteFolder();
                try {
                    timerStatic.cancel();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            private void deleteFolder() {
                //delete a folder
               return true;
            }
        }, 10000);
    }

}

我有一个创建一些文件夹的程序,我希望这些文件夹在一段时间后自动删除。文件夹的名称不是固定的,因此每次我调用这个类时,我都会为它创建一个新对象。

DeleteTimer obj = new DeleteTimer();
obj.start();

这在第一次尝试时效果很好,但是java.lang.IllegalStateException: Timer already cancelled当我尝试使用新对象运行它时会给出。请帮忙。

4

1 回答 1

4

timerStatic被声明static,这意味着所有的实例DeleteTimer共享相同的实例timerStatic

如果您同时删除方法 和static上的修饰符,这将阻止您的类的不同实例相互干扰。starttimerStatic

于 2011-08-25T13:02:34.170 回答