当前位置:网站首页>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);
}
}
边栏推荐
- How to successfully pass the CKA exam?
- Dapr 与 NestJs ,实战编写一个 Pub & Sub 装饰器
- PanGu-Coder:函数级的代码生成模型
- Windows 安装PostgreSQL
- postgresql之page分配管理(二)
- 实现集中式身份认证管理的案例
- Aeraki Mesh Joins CNCF Cloud Native Panorama
- SCHEMA solves the puzzle
- 初级必备:单例模式的7个问题
- Istio Meetup China: Full Stack Service Mesh - Aeraki Helps You Manage Any Layer 7 Traffic in an Istio Service Mesh
猜你喜欢

Alibaba Cloud Official Redis Development Specification

CAN通信标准帧和扩展帧介绍

How do we do full-link grayscale on the database?
![[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement](/img/fc/cd859efa69fa7b45f173de74c04858.png)
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement

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

How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
![leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]](/img/44/bf1d9b9d85939e73bc44be2f9701e1.png)
leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]

嵌入式开发:创建和使用可移植类型的7个技巧

windows IDEA + PHP+xdebug 断点调试

芝加哥丰田技术学院 | Leveraging Natural Supervision for Language Representation Learning and Generation(利用自然监督进行语言表示学习和生成)
随机推荐
shell 中的 分发系统 expect脚本 (传递参数、自动同步文件、指定host和要传输的文件、(构建文件分发系统)(命令批量执行))
Envoy source code flow chart
【StoneDB Class】Introduction Lesson 2: Analysis of the Overall Architecture of StoneDB
关于Request复用的那点破事儿。研究明白了,给你汇报一下。
AI目标分割能力,无需绿幕即可实现快速视频抠图
Process sibling data into tree data
阿里云官方 Redis 开发规范
ddl and dml in sql (the difference between database table and view)
线上问题排查常用命令,总结太全了,建议收藏!!
关于亚马逊测评,你了解多少?
字体反爬之好租
芝加哥丰田技术学院 | Leveraging Natural Supervision for Language Representation Learning and Generation(利用自然监督进行语言表示学习和生成)
PanGu-Coder:函数级的代码生成模型
将同级数据处理成树形数据
高仿项目协作工具【Worktile】,从零带你一步步实现组织架构、网盘、消息、项目、审批等功能
How to integrate 3rd party service center registration into Istio?
Programmer's self-cultivation
Beyond Compare 4 trial period expires
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
ECCV22|只能11%的参数就能优于Swin,微软提出快速预训练蒸馏方法TinyViT