java多线程之并发集合(BlockingQueue)

简介

java多线程之并发集合(BlockingQueue)_第1张图片

 

实现

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 queue = new LinkedBlockingQueue(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());//获取并删除,阻塞
	}

}

结果

java多线程之并发集合(BlockingQueue)_第2张图片

你可能感兴趣的:(Java并发和多线程操作)