Hello there I have slight problem and not sure where im going wrong with this.
I have 2 Threads X which prints repeatedly X and Y which prints Y repeatedly. Y needs to be printed after X.
I have derived from Semaphore class BinarySemaphore:
public class BinarySemaphore extends Semaphore {
public BinarySemaphore(int initial){
value = (initial>0) ? 1 : 0;
}
public synchronized void P() throws InterruptedException{
while (value==0){
wait();
}
value = 0;
notify();
}
public synchronized void V(){
value = 1;
notify();
}
}
X Thread class
public class xThread extends Thread implements Runnable{
private BinarySemaphore xSemaphore;
private BinarySemaphore ySemaphore;
public xThread(String myName, BinarySemaphore nSemaphoreX, BinarySemaphore nSemaphoreY ){
super(myName);
xSemaphore = nSemaphoreX;
ySemaphore = nSemaphoreY;
}
public void run(){
try{
xSemaphore.P();
System.out.println(getName());
ySemaphore.V();
}catch(InterruptedException E){
System.out.println("Thread X was interrupted");
}
}
}
Y Thread Class
public class yThread extends Thread implements Runnable{
private BinarySemaphore xSemaphore;
private BinarySemaphore ySemaphore;
public yThread(String myName, BinarySemaphore nSemaphoreX, BinarySemaphore nSemaphoreY ){
super(myName);
xSemaphore = nSemaphoreX;
ySemaphore = nSemaphoreY;
}
public void run(){
try{
ySemaphore.P();
System.out.println(getName());
xSemaphore.V();
}catch(InterruptedException E){
System.out.println("Thread Y was interrupted");
}
}
}
When I run these threads for 10seconds all I get is
X
Y
BUILD SUCCESSFUL (total time: 10 seconds)
What am I missing here ? Why doesn’t it keep alternating them for 10 seconds ?
This is because your threads are printing only once and then are terminated, like @reprogrammer suggested in his comment. You should insert a loop, something like: