java - 在某些情况发生后停止线程 ScheduledThreadPoolExecutor
问题描述
我想要一些线程池,每隔固定时间运行一些任务(这个线程池一直在获取任务)。每个任务调用一些 API 来获取一些值,该值可以为 null。只有当返回值为空时,我才希望任务再次运行(在固定时间之后)。否则,我不希望此任务再次运行。有没有办法做到这一点?我唯一想到的是使用 ScheduledThreadPoolExecutor 并从内部杀死特定线程,但我没有找到这样做的方法,我不确定这是一个好习惯。
谢谢!
解决方案
您可以安排一个任务并在安排下一个任务之前检查您的条件:
public class Solver {
final long delay = 500L;
String getSomeValue() {
if (Math.random() < 0.8) return "not-null";
return null;
}
void init() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(8);
Runnable runnable = new Runnable() {
@Override
public void run() {
long time = System.currentTimeMillis();
String value = getSomeValue();
System.out.println("" + value + " " + System.currentTimeMillis());
if (value == null) {
executor.schedule(this, delay - (System.currentTimeMillis() - time), TimeUnit.MILLISECONDS);
}
}
};
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
new Solver().init();
}
}
推荐阅读
- java - JavaFX - 如何检查鼠标是否已进入和或退出窗格?
- sql - 选择具有 datediff 1 和最新时间戳的行
- c# - 在另一个游戏对象的脚本上调用方法
- node.js - Webpack导入所有文件并将其导出为数组
- r - 凸 NMF 实现
- c# - Firebase 检索数据 - Android
- qt - Qt QML 如何找到形状的宽度和高度?
- python - ValueError: 以 10 为底的 long() 的无效文字:'$10592956'
- javascript - Which Event.target Property Should I Use?
- angular - 如何在Angular组件中向传单地图添加标记