public class MyStack { int size; Object[] elem; public MyStack() { size = 0; elem = new Object[1]; } public boolean isEmpty() { return size == 0; } private void grow() { Object[] newelem = new Object[2*size+1]; System.arraycopy(elem, 0, newelem, 0, size); elem = newelem; } public void moveTopToStack(MyStack other) { if (other.size == other.elem.length) other.grow(); other.elem[other.size++] = this.elem[--this.size]; } public void push(Object o) { if (size == elem.length) grow(); elem[size++] = o; } public String toString() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < size; i++) { sb.append(elem[i]); if (i < size-1) sb.append(","); } sb.append("]"); return sb.toString(); } public static void main(String[] param) throws InterruptedException { final MyStack a = new MyStack(); final MyStack b = new MyStack(); a.push("foo"); b.push("baz"); Thread t1 = new Thread("t1") { public void run() { for (int i = 0; i < 3; i++) { while (a.isEmpty()) yield(); a.moveTopToStack(b); } } }; Thread t2 = new Thread("t2") { public void run() { for (int i = 0; i < 3; i++) { while (b.isEmpty()) yield(); b.moveTopToStack(a); } } }; t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(a); System.out.println(b); } }