gpt4 book ai didi

java - 在 Java 中最推荐使用计时器的方法是什么

转载 作者:太空宇宙 更新时间:2023-11-04 13:02:52 25 4
gpt4 key购买 nike

我正在java中进行套接字编程。我必须在每个连接中使用计时器,并且我正在使用计时器,如下代码:

this.timeoutTask = new TimeoutTask();
this.timeoutTimer = Executors.newSingleThreadScheduledExecutor();
private void startTimer(ConnectionState state) {
int period;
connectionState = state;
period = connectionState.getTimeoutValue();
future = timeoutTimer.scheduleAtFixedRate(timeoutTask, period, period, TimeUnit.MILLISECONDS);
}
private void stopTimer() {

if (timeoutTimer != null) {
future.cancel(true);
}

}

private void shutdownTimer() {

timeoutTimer.shutdown();
timeoutTask.cancel();
}

我使用“stopTimer”函数来暂停计时器,使用“shutdownTimer”函数来删除计时器任务。但是,当像这样使用计时器时,有时会运行数千个计时器线程,因为数千个计时器同时处于 Activity 状态。防止此问题的最佳方法是什么?

最佳答案

您应该使用线程池,而不是为每个任务创建线程:

this.timeoutTask = new TimeoutTask();
static ScheduledExecutorService timeoutTimer = Executors.newScheduledThreadPool(10);


private void startTimer(ConnectionState state) {
int period;
connectionState = state;
period = connectionState.getTimeoutValue();
future = timeoutTimer.scheduleAtFixedRate(timeoutTask, period, period, TimeUnit.MILLISECONDS);
}

private void stopTimer() {
future.cancel(true);
}

现在任务将在线程池中的空闲线程中执行。

并且您不需要停止ExecutorService,只需使用future.cancel(true);取消任务

关于java - 在 Java 中最推荐使用计时器的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34788325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com