DelayQueue simple

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

public class DelayQueueTest {

	public static void main(String[] args) throws InterruptedException {
		DelayQueue<Customer> q = new DelayQueue<Customer>();
		Customer c1 = new Customer(5, "customer1");
		Customer c2 = new Customer(10, "customer2");
		q.put(c1);
		q.put(c2);

		int count = 1;
		while (true) {
			Thread.sleep(1000);
			Customer c = null;
			// q.take() 则会阻塞
			if (null != (c = q.poll())) {
				System.out.println("c : " + c.getName() + " , time:" + count+ "s");
			} else {
				System.out.println("get object " + c + " , time:" + count + "s");
			}
			count++;
			if (q.isEmpty()) {
				break;
			}
		}
		System.out.println("test finished");
	}

}

class Customer implements Delayed {
	private String name;

	// unit miutes
	private long delayTime;// 需要延时的时间

	public Customer(long delayTime, String name) {
		this.delayTime = System.nanoTime()
				+ TimeUnit.SECONDS.toNanos(delayTime);
		this.name = name;
	}

	@Override
	public int compareTo(Delayed o) {
		Customer c = (Customer) o;
		return this.delayTime > c.delayTime ? 1
				: (this.delayTime < c.delayTime ? -1 : 0);
	}

	@Override
	public long getDelay(TimeUnit unit) {
		long sys = System.nanoTime();
		// System.out.println("delayTime : " + delayTime
		// + " ,  System.nanoTime() " + sys);
		long minuts = delayTime - sys;
		return minuts;
	}

	public long getDelayTime() {
		return delayTime;
	}

	public String getName() {
		return name;
	}
}

 

 

 

get object null , time:1s
get object null , time:2s
get object null , time:3s
get object null , time:4s
c : customer1 , time:5s
get object null , time:6s
get object null , time:7s
get object null , time:8s
get object null , time:9s
c : customer2 , time:10s
test finished

 

你可能感兴趣的:(simple)