DelayQueue的用法

package com.fit.test;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayTest {

	static class DelayItem implements Delayed {

		public String	id;
		public long		daltime;
		public long		delay;
		public long		time;

		public DelayItem ( String id ) {
			this.id = id;
		}

		public DelayItem ( String id, long daltime, long delay ) {
			this.id = id;
			this.daltime = daltime;
			this.delay = delay;
			this.time = this.daltime + this.delay;
		}

		/**
		 * 预期时间在前的大:return 1
		 */
		@Override
		public int compareTo( Delayed o ) {
			long result = ( (DelayAlarm) o ).getTime() - this.getTime();
			if ( result < 0 )
				return 1;
			if ( result > 0 )
				return -1;
			return 0;
		}

		/**
		 * 预期时间-当前时间
		 */
		@Override
		public long getDelay( TimeUnit unit ) {
			return unit.convert( time * 1000L - System.currentTimeMillis(), TimeUnit.MILLISECONDS );
		}

		/**
		 * 根据流水号删除
		 */
		@Override
		public boolean equals( Object o ) {
			if ( o == null )
				return false;
			DelayAlarm a = (DelayItem ) o;
			if ( null == this.getId() || null == a.getId() )
				return false;
			return this.id.equals( a.getId() );
		}

		public String getId() {
			return id;
		}

		public long getDaltime() {
			return daltime;
		}

		public long getDelay() {
			return delay;
		}

		public long getTime() {
			return time;
		}

		public String toString() {
			return "{id:" + id + ", daltime:" + daltime + ", delay:" + delay + " , time:" + time + "}";
		}
	}

	//缓存队列
	public static DelayQueue<DelayItem>	queue	= new DelayQueue<DelayItem>();
	//
	public static volatile boolean			stop;

	public static void push( DelayItem a ) {
		if ( !queue.offer( a ) ) {
			System.out.println( "/- push error." );
		}
	}

	static class Consumer extends Thread {

		public void run() {
			while ( !stop ) {
				try {
					DelayItem a = queue.take();
					System.out.println( System.currentTimeMillis() / 1000L + "----" + a );
				} catch ( InterruptedException e ) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main( String[] args ) {
		new Consumer().start();
		long daltime = System.currentTimeMillis() / 1000;
		DelayItem a = new DelayItem ( "001", daltime, 1L );
		DelayItem b = new DelayItem ( "002", daltime, 3L );
		DelayItem c = new DelayItem ( "003", daltime, 5L );
		DelayItem d = new DelayItem ( "004", daltime, 2L );
		DelayItem f = new DelayItem ( "005", daltime, 10L );
		push( a );
		push( b );
		push( c );
		push( d );
		push( f );
		//移除003的告警
		DelayItem g = new DelayItem ( "003" );
		if ( queue.contains( g ) ) {
			queue.remove( g );
		}
	}
}

 

DelayQueue是Java的一个并发集合类,它实现了延迟队列,即只有在一定时间后才能从队列中获取元素。它的作用是在多线程应用程序中实现定时任务和调度任务。 以下是使用DelayQueue的基本步骤: 1. 创建一个实现Delayed接口的任务类,该接口定义了getDelay()方法,表示任务的延迟时间。 2. 创建一个DelayQueue对象,将任务添加到DelayQueue中。 3. 创建一个线程池,从DelayQueue中获取任务并执行。 4. 在任务的getDelay()方法返回0时,任务会被从DelayQueue中移除。 下面是一个简单的例子,演示了如何使用DelayQueue执行定时任务: ```java import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayQueueExample { public static void main(String[] args) { DelayQueue<DelayedTask> queue = new DelayQueue<>(); queue.add(new DelayedTask("task 1", 2, TimeUnit.SECONDS)); queue.add(new DelayedTask("task 2", 4, TimeUnit.SECONDS)); queue.add(new DelayedTask("task 3", 6, TimeUnit.SECONDS)); Thread thread = new Thread(() -> { while (true) { try { DelayedTask task = queue.take(); System.out.println("Execute task: " + task.getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.start(); } } class DelayedTask implements Delayed { private String name; private long delayTime; private long startTime; public DelayedTask(String name, long delayTime, TimeUnit unit) { this.name = name; this.delayTime = unit.toNanos(delayTime); this.startTime = System.nanoTime() + this.delayTime; } public String getName() { return name; } @Override public long getDelay(TimeUnit unit) { return unit.convert(startTime - System.nanoTime(), TimeUnit.NANOSECONDS); } @Override public int compareTo(Delayed o) { return Long.compare(this.startTime, ((DelayedTask) o).startTime); } } ``` 在这个例子中,我们创建了一个DelayQueue对象,并向其中添加了三个DelayedTask对象,分别在2秒、4秒和6秒后执行。我们还创建了一个线程,从DelayQueue中取出任务并执行。在DelayedTask的getDelay方法中,我们使用了System.nanoTime()方法获取当前时间,然后将任务的开始时间减去当前时间,得到任务的延迟时间。当任务的getDelay方法返回0时,它将从DelayQueue中移除,并被执行。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值