1. 程式人生 > >java多執行緒之併發集合(BlockingQueue)

java多執行緒之併發集合(BlockingQueue)

簡介

實現

package com.np.ota.test.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockQueueTest {

	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<String> queue = new LinkedBlockingQueue<String>(Integer.MAX_VALUE);
		//queue.add("121");
		queue.offer("122", 2, TimeUnit.SECONDS);//新增元素,新增超時時間
		
		//Retrieves and removes the head of this queue, or returns null if this queue is empty.
		System.out.println(queue.poll());//獲取並刪除,不阻塞
		//Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
		System.out.println(queue.peek());//獲取不刪除,不阻塞
		//Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
		System.out.println(queue.take());//獲取並刪除,阻塞
	}

}

結果