当前位置:网站首页>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);
}
}
边栏推荐
- markdown常用数学符号cov(markdown求和符号)
- 批量替换Word中的表格为图片并保存
- 为什么最大值加一等于最小值
- Do wildcard SSL certificates not support multiple domains?
- SQL函数 STR
- Aeraki Mesh Joins CNCF Cloud Native Panorama
- The basic knowledge of scripting language Lua summary
- 四足机器人软件架构现状分析
- leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]
- CAN通信的数据帧和远程帧
猜你喜欢
2022 Go ecosystem rpc framework Benchmark
Find objects with the same property value Cumulative number Summarize
CAN通信的数据帧和远程帧
Process sibling data into tree data
CAN通信标准帧和扩展帧介绍
安装apex报错
postgresql之page分配管理(一)
力扣160题,相交链表
Data frame and remote frame of CAN communication
CloudCompare & PCL ICP registration (point to face)
随机推荐
pandas connects to the oracle database and pulls the data in the table into the dataframe, filters all the data from the current time (sysdate) to one hour ago (filters the range data of one hour)
Feign 从注册到调用原理分析
初级必备:单例模式的7个问题
Qt get all files in a folder
iframe标签属性说明 详解[通俗易懂]
数字证书原理
Beyond Compare 4 trial period expires
批量任务导入到数据库中
MMF的初步介绍:一个规范化的视觉-语言多模态任务框架
数据挖掘-03
8. SAP ABAP OData 服务如何支持创建(Create)操作
Towhee 每周模型
SQL函数 STR
How to Integrate Your Service Registry with Istio?
高仿项目协作工具【Worktile】,从零带你一步步实现组织架构、网盘、消息、项目、审批等功能
快速幂---学习笔记
[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!
力扣160题,相交链表
易周金融分析 | 银行ATM机智能化改造提速;互联网贷款新规带来挑战
Meshlab & Open3D SOR filtering