当前位置:网站首页>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);
}
}
边栏推荐
- Grafana 9.0 released, Prometheus and Loki query builders, new navigation, heatmap panels and more!
- 观察者模式
- R language ggplot2 visualization: use the ggdensity function of the ggpubr package to visualize density plots, use the stat_central_tendency function to add mean vertical lines to the density and cust
- 批量任务导入到数据库中
- 大中型网站列表页翻页过多怎么优化?
- 初级必备:单例模式的7个问题
- STM32 CAN filter configuration details
- 脚本语言Lua的基础知识总结
- SCHEMA solves the puzzle
- SQL函数 %SQLUPPER
猜你喜欢
随机推荐
Simulation implementation of new of Js handwritten function
postgresql之page分配管理(二)
iframe标签属性说明 详解[通俗易懂]
字体反爬之好租
批量替换Word中的表格为图片并保存
MySQL调优
如何设计一个分布式 ID 发号器?
How to Integrate Your Service Registry with Istio?
How to Integrate Your Service Registry with Istio?
How to integrate 3rd party service center registration into Istio?
CAN通信的数据帧和远程帧
ECCV22|只能11%的参数就能优于Swin,微软提出快速预训练蒸馏方法TinyViT
Meshlab&Open3D SOR滤波
Visualization of lag correlation of two time series data in R language: use the ccf function of the forecast package to draw the cross-correlation function, and analyze the lag correlation according t
LeetCode_动态规划_中等_313.超级丑数
What is MNIST (what does plist mean)
通讯录(静态版)(C语言)(VS)
formatdatetime function mysql (date sub function)
Pytest e-commerce project combat (below)
AI目标分割能力,无需绿幕即可实现快速视频抠图