LinkedBlockingQueue的容量是没有上限的(说的不准确,在不指定时容量为Integer.MAX_VALUE,不要然的话在put时怎么会受阻呢),但是也可以选择指定其最大容量,它是基于链表的队列,此队列按 FIFO(先进先出)排序元素。 remove、element、offer 、poll、peek 其实是属于Queue接口。 测试队列 代码语言:
int element = 1;ExecutorService executorService = Executors.newFixedThreadPool(2);ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>(); Runnable offerTask = () -> queue.offer(element); Callable<Integer> pollTask = () -> { while (queue.peek() != null) { return queue.poll(...
Object el = queue.poll(); if(null == el){ System.out.println(Thread.currentThread().getName()+" is blocked, wait"); //this.wait(); //no need to invoked wait }else{ System.out.println(Thread.currentThread().getName()+" pool 1 element"); } Thread.sleep(50); } catch (Interrupt...
System.nanoTime() + nanos : 0L;//获取当前线程Thread w =Thread.currentThread();intspins = -1;//initialized after first item and cancel checksThreadLocalRandom randomYields =null;//bound if neededfor(;;) {//等待节点的当前数据Object item =s.item;//如果是take和timed poll方法,e为null。也...
Future<Integer> returnedElement = executorService.submit(pollTask); assertThat(returnedElement.get().intValue(), is(equalTo(element))); The first task,offerTask, adds an element to the queue, and the second task,pollTask,retrieve an element from the queue. The poll task additionallychecks the...
阻塞队列的实现包括ArrayBlockingQueue与LinkedBlockingQueue。相同点不做赘述,区别有以下几点: 1.初始化时,ArrayBlockingQueue必须指定队列最大容量,LinkedBlockingQueue不强制指定,若不指定,默认Interger.Max为最大容量。 2.ArrayBlockingQueue内部数据结构是数组:Element[],通过putIndex和takeIndex下标的循环移动控制队首和...