通过看Volley 网络框架发现了PriorityBlockingQueue,特来小用一下,哈哈。代码挺简单的。
public class RequestRunnable implements Runnable,Comparable{
public int mThreadNum;
public RequestRunnable(int num){
this.mThreadNum = num;
}
public void run() {
System.out.println("线程编号="+ mThreadNum);
}
public int compareTo(Object o) {
RequestRunnable runnable = (RequestRunnable) o;
return this.mThreadNum > runnable.mThreadNum ? 1 : -1;
}
}
/**
*
* PriorityBlockingQueue 没有边界,队列元素都必须实现Comparable 接口。
*
* 特点:队列调用take()取元素,若没有元素可取则阻塞,不往下执行,调用put()方法没有阻塞的情况,因为PriorityBlockingQueue是无界的队列。
*
*/
public class Main {
public static void main(String[] args){
int num = 0;
PriorityBlockingQueue mQueue = new PriorityBlockingQueue();
RequestRunnable request1 = new RequestRunnable(++num);
RequestRunnable request2 = new RequestRunnable(++num);
RequestRunnable request3 = new RequestRunnable(++num);
mQueue.put(request2);
mQueue.put(request1);
mQueue.put(request3);
try {
while(true){
RequestRunnable requestRunnable = (RequestRunnable)mQueue.take();
System.out.println("for "+ requestRunnable.mThreadNum);
requestRunnable.run();
if (mQueue.size() == 0) {
Thread.sleep(5000);
mQueue.put(new RequestRunnable(++num));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}