
Stack 线程安全的。先进后出机制,
Stack extends Vector{} Stack 继承至vector
public E push(E item) 入栈
1 2 3 4 5 6
|
public E (E item) { addElement(item); return item; }
|
1 2 3 4 5 6 7 8
|
public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; }
|
synchronized 给该方法区加上同步锁,两个线程同时执行该代码块时,只有一个线程可以执行该代码块,另一个线程必须等待前一个线程执行完成之后才能执行。
1 2 3 4 5 6 7
|
private void ensureCapacityHelper(int minCapacity) { if (minCapacity - elementData.length > 0) grow(minCapacity); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
|
private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
|
capacityIncrement 如果为0,则stack的容量成倍增长newCapacity = oldCapacity + oldCapacity ;否则newCapacity = oldCapacity + capacityIncrement
public synchronized E pop() 出栈
1 2 3 4 5 6 7 8 9 10
|
public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; }
|
1 2 3 4 5 6 7 8
|
public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
public synchronized void removeElementAt(int index) { modCount++; if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } else if (index < 0) { throw new ArrayIndexOutOfBoundsException(index); } int j = elementCount - index - 1; if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; elementData[elementCount] = null; }
|
public boolean empty() 判断元素是否为空
1 2 3
|
public boolean empty() { return size() == 0; }
|
public synchronized int search(Object o) 元素搜索
1 2 3 4 5 6 7 8
|
public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; }
|
1 2 3 4 5
|
public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public synchronized int lastIndexOf(Object o, int index) { if (index >= elementCount) throw new IndexOutOfBoundsException(index + " >= "+ elementCount); if (o == null) { for (int i = index; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; }
|
近期评论