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