当前位置:网站首页>Multithreading Case - Timer
Multithreading Case - Timer
2022-08-01 13:03:00 【Living_Amethyst】
定时器是什么
定时器It is also an important component in software development. 类似于一个 “闹钟”. 达到一个设定的时间之后, 就执行某个指定好的代码.
定时器是一种实际开发中非常常用的组件.
比如网络通信中, 如果对方 500ms 内没有返回数据, 则断开连接尝试重连.
比如一个 Map, 希望里面的某个 key 在 3s 之后过期(自动删除).
类似于这样的场景就需要用到定时器
标准库中的定时器
- 标准库中提供了一个 Timer 类. Timer 类的核心方法为 schedule .
- schedule 包含两个参数. 第一个参数指定即将要执行的任务代码, 第二个参数指定多长时间之后
执行 (单位为毫秒).
示例:
public static void main(String[] args) {
// java.util 里的一个组件
Timer timer = new Timer();
//schedule这个方法的效果 是 “安排一个任务”
//不是立刻执行 而是3000毫秒之后执行
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("This is a task to perform");
}
},3000);
}
模拟实现定时器
The analysis of many details is noted in the comments
//模拟实现 定时器
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;
class MyTask implements Comparable<MyTask>{
//what to do
private Runnable command;
//When will the task be done
private long time; //绝对时间
public MyTask (Runnable command,long after){
this.command = command;
//The time recorded here is an absolute timestamp,Not how long it will take to execute
this.time = System.currentTimeMillis()+after;
}
//执行任务的方法 Called directly internally Runnable 的 run 即可
public void run(){
command.run();
}
public long getTime() {
return time;
}
@Override
public int compareTo(MyTask o) {
//Hope the time is small 大的在后
return (int) (this.time - o.time);
}
}
class MyTimer {
//The lock object used to block waiting
private Object locker = new Object();
//Use a priority queue to hold several tasks
private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
// command:What is the task to perform
// after:How long before this task is executed
public void schedule(Runnable command,long after) {
MyTask myTask = new MyTask(command,after);
// 防止 Newly inserted task It was earlier than the task of the previous team leader,需要唤醒
synchronized (locker){
queue.put(myTask); //The join operation is also locked
locker.notify();
}
}
public MyTimer(){
// 启动一个线程
Thread t = new Thread(()->{
while (true){
//循环过程中 Keep trying to get the head element from the queue
//Determines whether the time of the head element is ready at that time,Execute when ready Do not execute if not ready
try {
synchronized (locker) {
MyTask myTask = queue.take();//Takes the head element of the team,The earliest task in time
long curTime = System.currentTimeMillis();
if (myTask.getTime() > curTime) {
//时间还没到
queue.put(myTask); //Put the task back on the queue
//队首的(最早执行的)Elemental time has not yet come,需要等待,不然一直循环 CPU空转 内耗
locker.wait(myTask.getTime() - curTime);
} else {
//时间到了 执行任务
myTask.run();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
public class Demo18 {
public static void main(String[] args) {
MyTimer myTimer = new MyTimer();
myTimer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("111");
}
},2000);
myTimer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("222");
}
},4000);
myTimer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("333");
}
},6000);
}
}
边栏推荐
- 8. SAP ABAP OData 服务如何支持创建(Create)操作
- 易周金融分析 | 银行ATM机智能化改造提速;互联网贷款新规带来挑战
- [5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
- 【讲座分享】“营收“看金融
- AI目标分割能力,无需绿幕即可实现快速视频抠图
- leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]
- Software designer test center summary (interior designer personal summary)
- 初级必备:单例模式的7个问题
- ECCV22|只能11%的参数就能优于Swin,微软提出快速预训练蒸馏方法TinyViT
- Envoy source code flow chart
猜你喜欢

那些利用假期学习的职场人,后来都怎么样了?

win10系统重装,无法登录进行同步的情况下chrome数据恢复

How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!

CloudCompare&PCL ICP配准(点到面)

找出相同属性值的对象 累加数量 汇总

HMS Core音频编辑服务音源分离与空间音频渲染,助力快速进入3D音频的世界

初级必备:单例模式的7个问题

Fault 007: The dexp derivative is inexplicably interrupted

这项工作事关中小学生生命安全!五部门作出联合部署

什么是一致性哈希?可以应用在哪些场景?
随机推荐
如何将第三方服务中心注册集成到 Istio ?
Pytest e-commerce project combat (below)
kubernetes之DaemonSet以及滚动更新
一文带你彻底厘清 Isito 中的证书工作机制
线上问题排查常用命令,总结太全了,建议收藏!!
Feign 从注册到调用原理分析
CAN通信标准帧和扩展帧介绍
Audio and Video Technology Development Weekly | 256
全链路灰度在数据库上我们是怎么做的?
Apex installation error
【StoneDB Class】Introduction Lesson 2: Analysis of the Overall Architecture of StoneDB
PanGu-Coder:函数级的代码生成模型
iframe标签属性说明 详解[通俗易懂]
SQL函数 SQUARE
通讯录(静态版)(C语言)(VS)
Favorites|Mechanical Engineer Interview Frequently Asked Questions
【StoneDB Class】入门第二课:StoneDB 整体架构解析
Data frame and remote frame of CAN communication
初级必备:单例模式的7个问题
bpmn-process-designer基础上进行自定义样式(工具、元素、菜单)