Answer:
import java.util.concurrent.Semaphore;
public class synchronization implements Runnable {
Semaphore b11 = new Semaphore(1);
@Override
//run method
public void run() {
boolean flvalue=false;
System.out.println("Started");
while(!flvalue) {
System.out.println("Thread is running");
}
System.out.println("Stopped");
}
//main method
public static void main(String args[]) {
final synchronization t11 = new synchronization();
Thread x1=new Thread(){
@Override
//run method
public void run(){
t11.mutualExclusion();
}
};
Thread x2=new Thread(){
@Override
//run method
public void run(){
t11.mutualExclusion();
}
};
Thread x3=new Thread(){
@Override
//run method
public void run(){
t11.mutualExclusion();
}
};
Thread x4=new Thread(){
@Override
//run method
public void run(){
t11.mutualExclusion();
}
};
Thread x5=new Thread(){
@Override
//run method
public void run(){
t11.mutualExclusion();
}
};
x1.start();
x2.start();
x3.start();
x4.start();
x5.start();
}
private void mutualExclusion() {
try {
b11.acquire();
//mutual value
String tn=Thread.currentThread().getName();
String numberOy= tn.replaceAll("[^0-9]", "");
int num=Integer.parseInt(numberOy)+1;
System.out.println("Thread "+num + " is running");
Thread.sleep(100);
} catch (InterruptedException ie11) {
ie11.printStackTrace();
} finally {
b11.release();
String tn11=Thread.currentThread().getName();
String numberOy= tn11.replaceAll("[^0-9]", "");
int numval=Integer.parseInt(numberOy)+1;
System.out.println("Thread "+numval + " completed...!!!");
}
}
}
Step-by-step explanation: