1. 程式人生 > 其它 >Java筆記-ConcurrentLinkedQueue的基本使用和注意事項

Java筆記-ConcurrentLinkedQueue的基本使用和注意事項

技術標籤:Javajavaqueue多執行緒

ConcurrentLinkedQueue這玩意用起來太方便了,這個的使用場景是在併發的時候使用。

這裡提供一個幾個簡單的例子:

    @Override
    public void run() {

        try {

            if(queue == null || queue.size() == 0){

//                System.out.println(Thread.currentThread() + " queue is null or size is zero");
                return;
            }

            while (!queue.isEmpty()){

                String sql = queue.poll().toString();
                //TODO 寫邏輯業務
                ......
                ......
            }
        }
        catch (SQLException e) {

            e.printStackTrace();
        }
    }

這裡有個注意事項,在遍歷ConcurrentLinkedQueue時不要使用for迴圈:

for(int i = 0; i < queue.size(); i++){
	
    //TODO
    ...
    ...
    ...
}

在多執行緒中這樣寫是會有問題的,請用下面的方式進行遍歷:

while(!queue.isEmpty()){
	
    String sql = queue.poll().toString();
    //TODO寫邏輯業務
    ......
    ......
}

這裡的poll(),也就是出佇列,這裡也就是基本的資料結構。