Wednesday, 21 October 2015

Java Thread example two


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Second sec = new Second(1);
Thread t = new Thread(sec);
Thread t1 = new Thread(sec);
t.start();
t1.start();
}

}



public class Second extends Thread{
int avail=1;
int req;
Second(int i){
this.req=i;
}
public void run(){
synchronized(this){
if((avail>0)&&(req==1)){
System.out.println("Allocating the seat");
avail=req-1;
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
System.out.println("No Seats");
}
}
}
}


output:-
Allocating the seat
No Seats

No comments:

Post a Comment