当前位置:网站首页>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);
}
}
边栏推荐
- [Community Star Selection] Issue 24 August Update Plan | Keep writing, refuse to lie down!More original incentive packages, as well as Huawei WATCH FIT watches!
- 实现集中式身份认证管理的案例
- 那些利用假期学习的职场人,后来都怎么样了?
- 大中型网站列表页翻页过多怎么优化?
- How to successfully pass the CKA exam?
- leetcode:1201. 丑数 III【二分 + 数学 + 容斥原理】
- Beyond Compare 4 trial period expires
- Find objects with the same property value Cumulative number Summarize
- 将同级数据处理成树形数据
- 找出相同属性值的对象 累加数量 汇总
猜你喜欢
初级必备:单例模式的7个问题
华盛顿大学、Allen AI 等联合 | RealTime QA: What's the Answer Right Now?(实时 QA:现在的答案是什么?)
批量替换Word中的表格为图片并保存
Find objects with the same property value Cumulative number Summarize
数据湖 delta lake和spark版本对应关系
达梦更换正式授权dm.key
Fault 007: The dexp derivative is inexplicably interrupted
如何使用 Authing 单点登录,集成 Discourse 论坛?
8. SAP ABAP OData 服务如何支持创建(Create)操作
四足机器人软件架构现状分析
随机推荐
重磅消息 | Authing 实现与西门子低代码平台的集成
Pytest电商项目实战(下)
SQL函数 STR
Aeraki Mesh became CNCF sandbox project
How to integrate 3rd party service center registration into Istio?
如何将第三方服务中心注册集成到 Istio ?
PanGu-Coder:函数级的代码生成模型
8. SAP ABAP OData 服务如何支持创建(Create)操作
态路小课堂丨浅谈优质光模块需要具备的条件!
并发编程10大坑,你踩过几个?
数据挖掘-04
库函数的模拟实现(strlen)(strcpy)(strcat)(strcmp)(strstr)(memcpy)(memmove)(C语言)(VS)
Windows 安装PostgreSQL
bat countdown code
NebulaGraph v3.2.0 性能报告
Deep understanding of Istio - advanced practice of cloud native service mesh
Towhee 每周模型
关于Request复用的那点破事儿。研究明白了,给你汇报一下。
How to Integrate Your Service Registry with Istio?
Tencent Cloud Native: Service Mesh Practice of Areaki Mesh in the 2022 Winter Olympics Video Live Application