Java筆記-ConcurrentLinkedQueue的基本使用和注意事項
阿新 • • 發佈:2020-12-09
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(),也就是出佇列,這裡也就是基本的資料結構。