天天看點

DelayQueue的簡單使用

我最近想用一個資料結構,可以定時從它裡面取出資料,發現java提供了DelayQueue,使用DelayQueue需要實作Delayed這個接口,而實作Delayed這個接口主要就是實作它的getDelay()和compareTo()這兩個方法,示例代碼如下:

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

class TestString implements Delayed{
	private String str;
	private long   timeout;
	TestString(String str,long timeout){
		this.str = str;
		this.timeout = timeout + System.nanoTime();
	}
	//傳回距離你自定義的逾時時間還有多少
	public long getDelay(TimeUnit unit){
		return unit.convert(timeout-System.nanoTime(), TimeUnit.NANOSECONDS);
	}
	//比較getDelay()函數的傳回值
	public int compareTo(Delayed other){
		 if (other == this) // compare zero ONLY if same object
             return 0;
         
		 TestString t = (TestString)other;
		 long d = (getDelay(TimeUnit.NANOSECONDS) - t.getDelay(TimeUnit.NANOSECONDS));
	     return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
	}
	void print(){
		System.out.println(str);
	}
}
public class TestCode {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<String> list = new ArrayList<String>();
		list.add("string 1");
		list.add("string 2");
		list.add("string 3");
		list.add("string 4");
		list.add("string 5");
		list.add("string 6");
		list.add("string 7");
		list.add("string 8");
		list.add("string 9");
		list.add("string 10");
		
        DelayQueue<TestString> queue = new DelayQueue<TestString>();
        
        long start = System.currentTimeMillis();
        for(int i = 0;i<10;i++){
        	queue.put(new TestString(list.get(i),
        			TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS)));
	        	try {
	    			 queue.take().print();
	    			 System.out.println("After " + 
	    					 (System.currentTimeMillis()-start) + " MilliSeconds");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
}
           

運作結果:

string 1

After 1012 MilliSeconds

string 2

After 2023 MilliSeconds

string 3

After 3026 MilliSeconds

string 4

After 4030 MilliSeconds

string 5

After 5033 MilliSeconds

string 6

After 6037 MilliSeconds

string 7

After 7040 MilliSeconds

string 8

After 8043 MilliSeconds

string 9

After 9046 MilliSeconds

string 10

After 10050 MilliSeconds