Monday, 29 November 2021

Three threads started at the same time .Priniting Order should be maintained , it should always print first,second,third

 package printorder;


import java.util.concurrent.Semaphore;

import java.util.function.IntConsumer;


public class PrintOrder {


private Semaphore first;

private Semaphore second;

private Semaphore third;


public PrintOrder() {

this.first = new Semaphore(1);

this.second = new Semaphore(1);

this.third = new Semaphore(1);


try {

this.second.acquire();

this.third.acquire();

} catch (InterruptedException e) {

e.printStackTrace();

}


}


public void first() throws InterruptedException {

this.first.acquire();

print("first");


this.second.release();

}


private void print(String string) {

System.out.println("Print order :" + string);


}


public void second() throws InterruptedException {

this.second.acquire();

print("second");


this.third.release();

}


public void third() throws InterruptedException {

this.third.acquire();

print("third");


this.first.release();

}


public static void main(String[] args) {


PrintOrder order = new PrintOrder();

Thread t1 = new Thread() {

public void run() {

System.out.println("Thread Running t1 "+Thread.currentThread().getName());

try {


order.third();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

Thread t2 = new Thread() {

public void run() {

System.out.println("Thread Running t2 "+Thread.currentThread().getName());

try {


order.second();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

Thread t3 = new Thread() {

public void run() {

System.out.println("Thread Running t3 "+Thread.currentThread().getName());

try {


order.first();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};


t1.start();

t2.start();

t3.start();


}


}


No comments:

Post a Comment

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...