用java 实现了一个线程安全的栈 (参考了tomcat源码)
public class SynchronizedStack<T> {
public static final int DEFAULT_SIZE = 128;
private static final int DEFAULT_LIMIT = -1;
private int size;
private final int limit;
/*
* Points to the next available object in the stack
*/
private int index = -1;
private Object[] stack;
public SynchronizedStack() {
this(DEFAULT_SIZE, DEFAULT_LIMIT);
}
public SynchronizedStack(int size, int limit) {
if (limit > -1 && size > limit) {
this.size = limit;
} else {
this.size = size;
}
this.limit = limit;
stack = new Object[size];
}
//互斥
public synchronized boolean push(T obj) {
index++;
if (index == size) {
if (limit == -1 || size < limit) {
expand();