约 200 字 预计阅读 1 分钟
1. 使用数组来实现栈
代码:
- 用数组来实现
- 用
CTL
来控制 - 测试类,参考
ConcurrentStackUsingArrayTest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| public class ConcurrentStackUsingArray<E> {
private final AtomicInteger CTL = new AtomicInteger(0);
private final AtomicReference<E[]> arr = new AtomicReference<>((E[]) new Object[10]);
private final AtomicInteger index = new AtomicInteger(0);
public void push(E e) {
while (!CTL.compareAndSet(0, 1)) {
Thread.yield();
}
while (index.get() >= arr.get().length) {
E[] oldArr = arr.get();
E[] newArr = (E[]) new Object[oldArr.length * 2];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
if (arr.compareAndSet(oldArr, newArr)) {
break;
}
}
arr.get()[index.getAndIncrement()] = e;
CTL.lazySet(0);
}
public E pop() {
while (!CTL.compareAndSet(0, 1)) {
Thread.yield();
}
E e = arr.get()[index.decrementAndGet()];
CTL.lazySet(0);
return e;
}
}
|
2. 代码实现位置
github 地址