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;
- import java.util.concurrent.atomic.AtomicReference;
- 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 AtomicReference<StackNode<T>> topNode = new AtomicReference<StackNode<T>>(null);
- public void push(T item) {
- StackNode<T> node, currentTop;
- do {
- node = new StackNode<T>(item);
- currentTop = topNode.get();
- if (currentTop != null) {
- node.setNext(currentTop);
- }
- } while (!topNode.compareAndSet(currentTop, node));
- }
- public T pop() {
- if (topNode.get() == null) {
- return null;
- }
- StackNode<T> currentTop;
- StackNode<T> newTop;
- do {
- currentTop = topNode.get();
- if (currentTop == null) {
- return null;
- }
- newTop = currentTop.getNext();
- } while (!topNode.compareAndSet(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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement