java 定时执行线程_Java实现多线程定时执行任务代码

本文介绍了如何在Java中利用PriorityBlockingQueue和TimerTask实现多线程定时执行任务。通过创建一个Worker线程,不断从队列中取出任务并判断是否达到执行时间,实现定时功能。
摘要由CSDN通过智能技术生成

Java实现多线程定时执行任务代码

发布时间:2020-05-30 12:23:37

来源:亿速云

阅读:144

作者:鸽子

Java多线程中的定时器(java.util.Timer)有定时执行任务的功能,通过设定定时器的间隔时间,会自动在此间隔后执行预先安排好的任务(java.util.TimerTask)。

timer.schedule(TimerTask,delay,interval time)

第一个参数是需要执行的任务。此类的类型为java.util.TimerTask。第二个参数是执行任务前等待时间,第三个参数是间隔时间(单位为毫秒)

package timer;

import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {

PriorityBlockingQueue queue = new PriorityBlockingQueue<>();

Worker worker;private static class Worker extends Thread {

PriorityBlockingQueue queue;

Worker(PriorityBlockingQueue queue) {

this.queue = queue;

}

@Override

public void run() {

while (true) {

try {

MyTimerTask task = queue.take();

long current = System.currentTimeMillis();

if (task.delay <= current) {

task.target.run();

} else {

queue.put(task);

Thread.sleep(task.delay - current);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

MyTimer() {

worker = new Worker(queue);

worker.start();

}

void execute(Runnable target, long delay) {

queue.put(new MyTimerTask(target, delay));

}

public static void main(String[] args) {

MyTimer timer = new MyTimer();

timer.execute(new Runnable() {

@Override

public void run() {

System.out.println("该起床了");

}

}, 2000);

System.out.println("另一个人");

}

}

package timer;

public class MyTimerTask implements Comparable {

Runnable target;

long delay;MyTimerTask(Runnable target, long delay) {

this.target = target;

this.delay = System.currentTimeMillis() + delay;//延时后的时刻

}

@Override

public int compareTo(MyTimerTask o) {

if (delay == o.delay) {

//延时后的时刻

return 0;

} else if (delay < o.delay) {

return -1;

} else {

return 1;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值