Skip to content

Instantly share code, notes, and snippets.

@nil96
Created June 10, 2023 18:46
Show Gist options
  • Save nil96/54b69deb784a387288fb039e1ae50e64 to your computer and use it in GitHub Desktop.
Save nil96/54b69deb784a387288fb039e1ae50e64 to your computer and use it in GitHub Desktop.
import java.util.Random;
import java.util.concurrent.Semaphore;
class OrderedPrinting {
Semaphore s1 = new Semaphore(1);
public void printFirst() throws InterruptedException {
synchronized (this) {
while (s1.availablePermits() != 1) {
wait();
}
System.out.println("First");
s1.release();
notifyAll();
}
}
public void printSecond() throws InterruptedException {
synchronized (this) {
while (s1.availablePermits() != 2) {
wait();
}
System.out.println("Second");
s1.release();
notifyAll();
}
}
public void printThird() throws InterruptedException {
synchronized (this) {
while (s1.availablePermits() != 3) {
wait();
}
System.out.println("Third");
s1.release();
s1 = new Semaphore(1);
notifyAll();
}
}
}
class Demonstration {
public static void main(String args[]) throws InterruptedException {
OrderedPrinting orderedPrinting = new OrderedPrinting();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try{
orderedPrinting.printFirst();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try{
orderedPrinting.printSecond();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
try{
orderedPrinting.printThird();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
});
Thread t1_1 = new Thread(new Runnable() {
@Override
public void run() {
try{
orderedPrinting.printFirst();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
});
Thread t2_2 = new Thread(new Runnable() {
@Override
public void run() {
try{
orderedPrinting.printSecond();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
});
Thread t3_3 = new Thread(new Runnable() {
@Override
public void run() {
try{
orderedPrinting.printThird();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
});
t3.start();
Thread.sleep(1000);
t1.start();
Thread.sleep(1000);
t2.start();
t3_3.start();
Thread.sleep(1000);
t1_1.start();
Thread.sleep(1000);
t2_2.start();
t3.join();
t1.join();
t2.join();
t3_3.join();
t1_1.join();
t2_2.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment