还是年轻啊,知识储备严重不足.
今天大佬让我实现以下XXX.
每次用户请求都会判断当前值在不在集合里面,集合数据来自于数据库,不用做缓存,每隔几分钟从数据库load一下数据放到内存就行.
我一脸懵逼,操作内存?我不会啊.
而且没有用spring框架,我也不会定时任务啊…Timer什么的记不住要现场查一下吗?
然后大佬帮我写了一下…..我现在来复习一下.
场景模拟如下:
每隔X段时间,随机生成一些随机数放到内存中.会有用户请求接口来查看某个值是否在其中
.
具体实现了:
每隔5s,随机生成3个随机数替换掉原来的,然后启动一个死循环不断判断2是否在这次的list中.
``
其实比较简单,当时一脸懵逼没想起来,也是对已有知识掌握的不够熟悉.
package daily;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Created by pfliu on 2019/03/29.
*/
public class ScheduleThreadTest {
private static final AtomicReference<List<Integer>> list = new AtomicReference<>(new ArrayList<>());
public static void main(String[] args) throws InterruptedException {
// 线程池执行定时任务
ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(1);
schedule.scheduleWithFixedDelay(() -> {
// 每隔5秒生成3个1-10的数字,放进list里面
List<Integer> integers = new ArrayList<>();
for (int i = 0; i < 3; ++i) {
integers.add(new Random().nextInt(10));
}
list.set(integers);
System.out.println("now list = " + integers.toString());
}, 0, 5, TimeUnit.SECONDS);
// 测试程序,每一秒测试一下2是否在当前的list中.
while (true) {
int target = 2;
System.out.println(list.get().contains(target));
Thread.sleep(1000);
}
}
}
要活学活用啊亲.
完.
2019-01-28
以上皆为个人所思所得,如有错误欢迎评论区指正。
欢迎转载,烦请署名并保留原文链接。
联系邮箱:huyanshi2580@gmail.com
更多学习笔记见个人博客——>呼延十
var gitment = new Gitment({ id: '用线程池执行定时任务', // 可选。默认为 location.href owner: 'hublanker', repo: 'blog', oauth: { client_id: '2297651c181f632a31db', client_secret: 'a62f60d8da404586acc965a2ba6a6da9f053703b', }, }) gitment.render('container')
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有