Wednesday, June 28, 2017

Stack Push Pop Threads

Tags

Code:

class stack {
int[] a;
int top=-1;

public stack(int size) {
a=new int[size];
}
void push(int x){
if(top==a.length-1){
System.out.println("Stack Full");
}
else{
a[++top]=x;
}
}
int pop(){
if(top<0){
System.out.println("Empty Stack");
return 0;
}
else {
return a[top--];
}
}
}
class Pop extends Thread{
stack sRef;
Pop(stack s){
sRef=s;
}
public void run(){
synchronized(sRef){

try {
sRef.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}


for(int i=0;i<sRef.a.length;i++){
System.out.println("Value: "+sRef.pop());
}

}
}
}
class Push extends Thread{

stack sRef;

public Push(stack s) {
sRef=s;
}
public void run(){
synchronized(sRef){
for(int i=0;i<sRef.a.length;i++){
sRef.push(i);
}
sRef.notify();
}
}
}
public class StackDemo {

public static void main(String[] nt) {
System.out.println("--Main Started--");
stack s=new stack(23);

Pop pRef=new Pop(s);
Push puRef=new Push(s);

pRef.start();
puRef.start();

try {

puRef.join();
pRef.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("--Main Finished--");

}

}

Output: