Javaのループキュー(リングバッファ、RingBuffer)

3240 ワード

ループキュー(リングバッファ、RingBuffer)を作成します.実際の要素は配列に存在し、配列のポインタを操作し、要素を移動しません.
スレッドは安全で、書きながら読むことができます.
/*******************************************************************************
 * Copyright (c) 2015, 2015  Technologies Corporation.
 ******************************************************************************/
package queueCircle;

import java.util.Arrays;

/**
 * @Created Apr 7, 2015 11:06:21 AM
 * @Description
 *              

* ( 、RingBuffer), , , */ public class CircleQueue { /** * ( ) */ private final int DEFAULT_SIZE = 1000; /** * ( ) */ public int capacity; /** * : */ public Object[] elementData; /** * ( ) */ public int head = 0; /** * */ public int tail = 0; /** * */ public CircleQueue() { capacity = DEFAULT_SIZE; elementData = new Object[capacity]; } /** * * * @param initSize */ public CircleQueue(final int initSize) { capacity = initSize; elementData = new Object[capacity]; } /** * ( ) */ public int size() { if (isEmpty()) { return 0; } else if (isFull()) { return capacity; } else { return tail + 1; } } /** * */ public void add(final T element) { if (isEmpty()) { elementData[0] = element; } else if (isFull()) { elementData[head] = element; head++; tail++; head = head == capacity ? 0 : head; tail = tail == capacity ? 0 : tail; } else { elementData[tail + 1] = element; tail++; } } public boolean isEmpty() { return tail == head && tail == 0 && elementData[tail] == null; } public boolean isFull() { return head != 0 && head - tail == 1 || head == 0 && tail == capacity - 1; } public void clear() { Arrays.fill(elementData, null); head = 0; tail = 0; } /** * @return ( index=0) */ public Object[] getQueue() { final Object[] elementDataSort = new Object[capacity]; final Object[] elementDataCopy = elementData.clone(); if (isEmpty()) { } else if (isFull()) { int indexMax = capacity; int indexSort = 0; for (int i = head; i < indexMax;) { elementDataSort[indexSort] = elementDataCopy[i]; indexSort++; i++; if (i == capacity) { i = 0; indexMax = head; } } } else { // elementDataSort = elementDataCopy;// , for (int i = 0; i < tail; i++) { elementDataSort[i] = elementDataCopy[i]; } } return elementDataSort; } /** * */ public static void main(final String[] args) { final CircleQueue queue = new CircleQueue(10); for (int i = 0; i < 99; i++) { queue.add(i); } final Object[] queueArray = queue.getQueue(); System.out.println(" :"); for (final Object o : queueArray) { System.out.println(o); } System.out.println("capacity: " + queue.capacity); System.out.println("size: " + queue.size()); System.out.println("head index: " + queue.head); System.out.println("tail index: " + queue.tail); } }


.