java隊列ConcurrentLinkedQueue的使用

來源:互聯網
上載者:User
ConcurrentLinkedQueue隊列是一種先進先出模式的隊列,下面示範一個demo:


先建立一個測試pojo,Log.java兩個欄位,加上get、set方法
private Date date;
private String value;


然後建立隊列類,如下:
package com.newer.queue;


import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;




/**
 * 用於記錄日誌的隊列,ConcurrentLinkedQueue <br/>
 * 此隊列按照 FIFO(先進先出)原則對元素進行排序,詳見J2SE_API或JDK
 * @author RSun
 * 2012-2-22下午05:05:19
 */
public class SystemLogQueue {

private static Queue<Log> log_Queue;
static{
if (null == log_Queue) {
log_Queue = new ConcurrentLinkedQueue<Log>(); //基於連結節點的無界安全執行緒隊列
}
}


/** 初始化建立隊列 **/
public static void init() {
if (null == log_Queue) {
log_Queue = new ConcurrentLinkedQueue<Log>(); //基於連結節點的無界安全執行緒隊列
}
}


/**
* 添加到隊列方法,將指定元素插入此隊列的尾部。
* @param log Log對象
* @return 成功返回true,否則拋出 IllegalStateException
*/
public static boolean add(Log log) {
return (log_Queue.add(log));
}


/** 擷取並移除此隊列的頭 ,如果此隊列為空白,則返回 null */
public static Log getPoll() {
return (log_Queue.poll());
}

/** 擷取但不移除此隊列的頭;如果此隊列為空白,則返回 null **/
public static Log getPeek() {
return (log_Queue.peek());
}

/** 判斷此隊列是否有元素 ,沒有返回true **/
public static boolean isEmpty() {
return (log_Queue.isEmpty());
}


/** 擷取size,速度比較慢 **/
public static int getQueueSize() {
return (log_Queue.size());
}



public static void main(String[] args) {
System.out.println("隊列是否有元素:" + !isEmpty());
Log log = new Log();
log_Queue.add(log);

System.out.println("隊列是否有元素:" + !isEmpty());
Log log2 = new Log();
log2.setDate(new Date());
log2.setValue("哈哈哈");
log_Queue.add(log2);
System.out.println("隊列元素個數:" + getQueueSize());

Log l = getPeek();
System.out.println("\n擷取隊列資料:" + l.getValue() + "---" + l.getDate());
System.out.println("隊列元素個數:" + getQueueSize());

for (int i = 0; i < 2; i++) {
Log l2 = getPoll();
if(l2 != null){
System.out.println("\n擷取隊列資料並刪除:" + l2.getValue() + "---" + l2.getDate());
}
System.out.println("隊列元素個數:" + getQueueSize());
}


// 隊列是否有元素:false
// 隊列是否有元素:true
// 隊列元素個數:2
// 擷取隊列資料:null---null
// 隊列元素個數:2
// 擷取隊列資料並刪除:null---null
// 隊列元素個數:1
// 擷取隊列資料並刪除:哈哈哈---Thu Nov 15 13:58:02 CST 2012
// 隊列元素個數:0

}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.