Generic Stack Class with Synchronized methods
import java.util.ArrayList;
public class MyGenericStack<E> {
E obj;
int capacity;
ArrayList<E> list;
public MyGenericStack(int c) {
capacity=c;
list= new ArrayList<E>(capacity);
}
public synchronized boolean push(E o){
try { Thread.sleep(1000); } catch (Exception e) { System.out.println(e);
}
if (list.size()<20) {
list.add(o);
notifyAll();
return true;
}
return false;
}
public synchronized E pop() {
try { Thread.sleep(1000); } catch (Exception e) { System.out.println(e); }
if (isEmpty()) {
try {
System.out.println("Stack is empty.. Please wait..!");
wait();
} catch (Exception e) {
System.out.println(e);
}
}
obj= list.remove(list.size()-1);
return obj;
}
// If required then uncomment this method
/* public synchronized void show() {
System.out.println("size of stack is : "+ list.size());
if (list.size()>0) {
for (E o : list)
{
System.out.println(o);
}
}
else {
System.out.println("No elements in stack...");
}
}
*/
public boolean isEmpty() { return list.isEmpty(); }
public boolean isFull() { return list.size()>20 ;}
}
Comments
Post a Comment