Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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) {
- 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) {
- }
- for (int j = 0; j < 1000; j++) {
- stack.pop();
- }
- }
- });
- }
- } finally {
- executor.shutdown();
- executor.awaitTermination(10, TimeUnit.SECONDS);
- }
- }
- }
- 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 Stack<T> {
- private StackNode<T> top;
- public synchronized void push(T item) {
- StackNode<T> node = new StackNode<T>(item);
- StackNode<T> currentTop = this.top;
- if (currentTop != null) {
- node.setNext(currentTop);
- }
- this.top = node;
- }
- public synchronized T pop() {
- if (this.top == null) {
- return null;
- }
- StackNode<T> currentTop = this.top;
- this.top = currentTop.getNext();
- return currentTop.getValue();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement