public class YhdgRoom extends TimerTask {    static SimpleDateFormat fmt = new SimpleDateFormat("[yyyy-MM-dd HH:mm]");
    AccountManager am = AccountManager.getInstance();    public String sid = "";
    public String name = "";
    public YhdgGroup xx = new YhdgGroup(this, 0); //玩家
    public YhdgGroup yy = new YhdgGroup(this, 1); //机器人
    public YhdgGroup[] Groups = new YhdgGroup[] {xx, yy};
    public int loseGroupId = -1; //0 :xx负  1:yy负
    public int leaveRoomUserNum = 0; //游戏结束后,已经有几个人离开游戏
    public long lasttime;
    private long createTime;//房间创建时间
    public int maxPlayers = 2;
    public int limitTime = 10;//时间限制,默认36分钟
    public int roomState = -1;//0:准备好了 1:本轮结束了
    public YhdgMsg[] msgs = new YhdgMsg[80];
    public Timer timer = null;
    public HttpSession session;
    
    public YhdgRoom(String sessionid, String gameid, Timer timer, HttpSession session) {
     this.sid = sessionid;
     this.name = gameid;
     this.timer = timer;
     System.out.println("构造函数中的timer:" + timer);
     this.session = session;
        GameLoad.getUnit();
        lasttime = System.currentTimeMillis();
        createTime = System.currentTimeMillis();
    }
    
public void run() {
if (System.currentTimeMillis() - createTime > (limitTime*1000)) {
System.out.println("进入时间判断的分支了");
over();
timer.cancel();
//跳转到提示页面,房间已经超时,根据分数判断胜负
} else if (roomState == 1) {
System.out.println("进入判断roomState分支了");
timer.cancel();
//跳转到提示页面,游戏已经结束,根据分数判断胜负
} else {
//运行其他方法
System.out.println("run里的");
}
}

public void over () {
session.removeAttribute(sid);
System.out.println("进入了over方法了");
}
}
这段代码在满足System.currentTimeMillis() - createTime > (limitTime*1000)后执行了timer.cancel,可是在不执行任何操作的情况下,容器会自己报错,我用的是resin
java.lang.illegalstateexception timer already cancelled
请问为什么当时不报错,而过了一段时间才自己报错啊,这个是什么错呢,怎么解决掉呢?

解决方案 »

  1.   

    UP,你试一试不cancel的效果,我很怀疑在JavaEE的容器里面起Thread,Timer什么的。
      

  2.   

    你的代码有点糊涂了吧.
    YhdgRoom 是要用Timer来执行的task,
    你怎么能在YhdgRoom 里面cancel Timer呢,
    Timer的cancel方法你new Timer那里去..
      

  3.   

    默认情况下,只要一个程序的timer线程在运行,那么这个程序就会保持运行。当然,你可以通过以下四种方法终止一个timer线程:
    调用timer的cancle方法。你可以从程序的任何地方调用此方法,甚至在一个timer task的run方法里。 
    让timer线程成为一个daemon线程(可以在创建timer时使用new Timer(true)达到这个目地),这样当程序只有daemon线程的时候,它就会自动终止运行。 
    当timer相关的所有task执行完毕以后,删除所有此timer对象的引用(置成null),这样timer线程也会终止。 
    调用System.exit方法,使整个程序(所有线程)终止。 
    =============================
    我在网上搜索的我以前没用过timertask
      

  4.   

    不用cancel的话,这个程序就一直跑下去,不报错的,但是如果用了的话,过半个小时左右,容器就报那个从自己关闭了,而这半个小时里访问别的网页一点问题都没有,就跟没有错误似的