小编vaz*_*zor的帖子

Java静态定时器可以处理多个调用cancel()的TimerTasks吗?

所以我正在运行Java服务器,在一个类中我有一个静态Timer.然后我有另一个类,它在程序的整个生命周期中创建和销毁了许多实例,每个实例都有自己的TimerTask(使用静态Timer).当一个实例被销毁时,它会在TimerTask上调用cancel().

问题是,我不确定这是不是很好的设计,而且在实例创建和调度TimerTask时我也会遇到错误:

     java.lang.IllegalStateException: Timer already cancelled.
Run Code Online (Sandbox Code Playgroud)

这是一些显示我的意思的代码.

/**
 * Starts scheduled tasks using TimerTask
 */
private void initTasks()
{
    // room heartbeat thread:  start immediately, run once every second
    roomHeartbeatTask = new RoomHeartbeatTask(this);
    RoomListExtension.roomHeartbeat.schedule(roomHeartbeatTask, 0, 1000);
    // add additional tasks here
}

/**
 * Cancels all tasks that have been started by this extension
 */
private void cancelTasks()
{
    roomHeartbeatTask.cancel();
}
Run Code Online (Sandbox Code Playgroud)

java multithreading timer task

3
推荐指数
1
解决办法
7551
查看次数

标签 统计

java ×1

multithreading ×1

task ×1

timer ×1