Skip to content

Instantly share code, notes, and snippets.

@nomoa
Created April 12, 2023 21:44
Show Gist options
  • Save nomoa/e7825311021bffbd3a68c62c60976b0a to your computer and use it in GitHub Desktop.
Save nomoa/e7825311021bffbd3a68c62c60976b0a to your computer and use it in GitHub Desktop.
public static class UsingSemaphore {
volatile static boolean check = true;
volatile static boolean producerStarted = false;
volatile static boolean consumerStarted = false;
public static void main(String args[]) throws InterruptedException {
Semaphore semCon = new Semaphore(0);
Semaphore semProd = new Semaphore(1);
Queue<Integer> q = new LinkedList<>();
// Producer lambda
Runnable producer = () -> {
while (check) {
producerStarted = true;
try {
semProd.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Random rand = new Random();
q.add(rand.nextInt(10));
}finally {
semCon.release();
}
}
};
//Consumer lambda
Runnable consumer = () -> {
while (check) {
consumerStarted = true;
try {
semCon.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("Consumer item " + q.remove());
}finally {
semProd.release();
}
}
};
ThreadGroup pg = new ThreadGroup("PG");
ThreadGroup cg = new ThreadGroup("CG");
Thread p1 = new Thread(pg, producer, "p1");
Thread c1 = new Thread(cg, consumer, "c1");
producerStarted = false;
consumerStarted = false;
check = true;
p1.start();
c1.start();
Thread.sleep(10);
while (!consumerStarted || !producerStarted) {
Thread.sleep(1);
}
check = false;
p1.join();
c1.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment