class Stack { private int[] array; private int stackTop; Object lock; Stack(int capacity) { array = new int[capacity]; stackTop = -1; lock = new Object(); } public synchronized boolean push(int element) { if (isFull()) return false; ++stackTop; try { Thread.sleep(1000); } catch (Exception e) {} array[stackTop] = element; return true; } public synchronized int pop() { if (isEmpty()) return Integer.MIN_VALUE; int obj = array[stackTop]; array[stackTop] = Integer.MIN_VALUE; try { Thread.sleep(1000); } catch (Exception e) { } stackTop--; return obj; } public boolean isEmpty() { return stackTop < 0; } public boolean isFull() { return stackTop >= array.length - 1; } } public class ThreadStack { public static void main(String[] args) { System.out.println("Main is starting"); Stack st = new Stack(5); new Thread(()->{ int counter =0; while(++counter<5){ System.out.println("pushed: "+st.push(100)); } },"pusher").start(); new Thread(()->{ int counter =0; while(++counter<5){ System.out.println("pushed: "+st.pop()); } },"popper").start(); System.out.println("Main is ending!"); } }