我正在修改我的服务器,以便每次接受连接时,它都应该使用回调函数在线程中注册超时事件。超时可以是任意数字。
只有一个超时线程(每个连接没有分配给一个单独的超时线程)。
我该如何去做呢?我正在考虑在 main 中启动一个线程,但不确定如何用它注册超时事件以及如何传递参数。
最佳答案
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
void registerCallback() {
ses.schedule(new MyCommand(), 30, TimeUnit.SECONDS);
}
它返回 Future
如果您愿意,可以使用它来取消执行,或者获取 MyCommand
返回的值。
如果您想要安排一个及时重复的命令,您可以使用其他安排方法:scheduleAtFixedRate
和 scheduleWithFixedDelay
。
如果您只需要在某些条件下重新安排,或者以不同的速率或间隔进行重新安排,我使用的一种技术是将 ScheduledExecutorService
传递给您的命令(即 new MyCommand( ses)
) 并让它重新安排自己或具有适当延迟的新命令:
class MyCommand implements Runnable {
private final ScheduledExecutorService ses;
MyCommand(ScheduledExecutorService ses) { this.ses = ses; }
private boolean shouldReschedule() { ... }
private int getRescheduleTimeoutMs() { ... }
@Override void run() {
// do work
...
// reschedule if needed
if (shouldReschedule()) {
// reschedule this command:
ses.schedule(this, getRescheduleTimeoutMs(), TimeUnit.MILLISECONDS);
// or else a new one:
ses.schedule(new MyCommand(ses), ...);
}
}
}
关于java - 使用回调函数在线程中注册事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9371900/