Advertisement
Jaydeep999997

Non Blocking Queue - Monitor

Nov 2nd, 2024
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | Source Code | 0 0
  1. import java.util.concurrent.CyclicBarrier;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.TimeUnit;
  5.  
  6. class Demonstration {
  7.   public static void main(String[] args) {
  8.     Stack<Integer> stack = new Stack<Integer>();
  9.     ExecutorService executor = Executors.newFixedThreadPool(20);
  10.     int numThreads = 2;
  11.     CyclicBarrier barrier = new CyclicBarrier(numThreads);
  12.     try {
  13.       for (int i = 0; i < numThreads; i++) {
  14.         executor.Submit(
  15.             new Runnable() {
  16.               @Override
  17.               public void run() {
  18.                 for (int j = 0; j < 1000; j++) {
  19.                   stack.push(j);
  20.                 }
  21.                 try {
  22.                   barrier.await();
  23.                 } catch (InterruptedException e) {
  24.  
  25.                 }
  26.  
  27.                 for (int j = 0; j < 1000; j++) {
  28.                   stack.pop();
  29.                 }
  30.               }
  31.             });
  32.       }
  33.     } finally {
  34.       executor.shutdown();
  35.       executor.awaitTermination(10, TimeUnit.SECONDS);
  36.     }
  37.   }
  38. }
  39.  
  40. class StackNode<T> {
  41.   private T value;
  42.   StackNode<T> next;
  43.  
  44.   public StackNode(T value) {
  45.     this.value = value;
  46.   }
  47.  
  48.   public void setNext(StackNode<T> next) {
  49.     this.next = next;
  50.   }
  51.  
  52.   public T getValue() {
  53.     return this.value;
  54.   }
  55.  
  56.   public StackNode<T> getNext() {
  57.     return this.next;
  58.   }
  59. }
  60.  
  61. class Stack<T> {
  62.   private StackNode<T> top;
  63.  
  64.   public synchronized void push(T item) {
  65.     StackNode<T> node = new StackNode<T>(item);
  66.     StackNode<T> currentTop = this.top;
  67.     if (currentTop != null) {
  68.       node.setNext(currentTop);
  69.     }
  70.     this.top = node;
  71.   }
  72.  
  73.   public synchronized T pop() {
  74.     if (this.top == null) {
  75.       return null;
  76.     }
  77.     StackNode<T> currentTop = this.top;
  78.     this.top = currentTop.getNext();
  79.     return currentTop.getValue();
  80.   }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement