Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.CyclicBarrier;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- class Demonstration {
- public static void main(String[] args) throws Exception {
- Stack<Integer> stack = new Stack<Integer>();
- ExecutorService executor = Executors.newFixedThreadPool(20);
- int numThreads = 2;
- CyclicBarrier barrier = new CyclicBarrier(numThreads);
- try {
- for (int i = 0; i < numThreads; i++) {
- executor.submit(
- new Runnable() {
- @Override
- public void run() {
- for (int j = 0; j < 1000; j++) {
- stack.push(j);
- }
- try {
- barrier.await();
- } catch (InterruptedException e) {
- } catch (BrokenBarrierException e) {
- }
- for (int j = 0; j < 1000; j++) {
- stack.pop();
- }
- }
- });
- }
- } finally {
- executor.shutdown();
- executor.awaitTermination(10, TimeUnit.SECONDS);
- }
- }
- }
- class Stack<T> {
- private SimulatedCompareAndSwap<StackNode<T>> topNode =
- new SimulatedCompareAndSwap<StackNode<T>>(null);
- public void push(T item) {
- StackNode<T> node, currentTop;
- do {
- node = new StackNode<T>(item);
- currentTop = topNode.getValue();
- if (currentTop != null) {
- node.setNext(currentTop);
- }
- } while (topNode.compareAndSwap(currentTop, node));
- }
- public T pop() {
- if (topNode.getValue() == null) {
- return null;
- }
- StackNode<T> currentTop;
- StackNode<T> newTop;
- do {
- currentTop = topNode.getValue();
- if (currentTop == null) {
- return null;
- }
- newTop = currentTop.getNext();
- } while (topNode.compareAndSwap(currentTop, newTop));
- return currentTop.getValue();
- }
- }
- class StackNode<T> {
- private T value;
- StackNode<T> next;
- public StackNode(T value) {
- this.value = value;
- }
- public void setNext(StackNode<T> next) {
- this.next = next;
- }
- public T getValue() {
- return this.value;
- }
- public StackNode<T> getNext() {
- return this.next;
- }
- }
- class SimulatedCompareAndSwap<T> {
- private T value;
- public SimulatedCompareAndSwap(T value) {
- this.value = value;
- }
- synchronized T getValue() {
- return this.value;
- }
- public synchronized boolean compareAndSwap(T expected, T newValue) {
- if (expected == null && value == null) {
- value = newValue;
- return true;
- }
- if (!expected.equals(value)) {
- return false;
- }
- this.value = newValue;
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement