Skip to content

Instantly share code, notes, and snippets.

@GorvGoyl
Created July 12, 2015 21:25
Show Gist options
  • Save GorvGoyl/6e5b16c10bdcfd59a25c to your computer and use it in GitHub Desktop.
Save GorvGoyl/6e5b16c10bdcfd59a25c to your computer and use it in GitHub Desktop.
Producer Consumer problem - Solution using Semaphore in Java
import java.util.concurrent.Semaphore;
class Queue {
int value;
static Semaphore semProd = new Semaphore(1); //Producer is first getting lock on producer semaphore
static Semaphore semCon = new Semaphore(0);
void get() {
try {
semCon.acquire();
} catch (InterruptedException e) {
}
System.out.println("Got: " + value);
semProd.release();
}
void put(int n) {
try {
semProd.acquire();
} catch (InterruptedException e) {
}
this.value = n;
System.out.println("Put: " + n);
semCon.release();
}
}
class Producer implements Runnable {
Queue q;
Producer(Queue q) {
this.q = q;
new Thread(this).start();
}
public void run() {
for (int i = 1; i < 11; i++)
q.put(i);
}
}
class Consumer implements Runnable {
Queue q;
Consumer(Queue q) {
this.q = q;
new Thread(this).start();
}
public void run() {
for (int i = 1; i < 11; i++)
q.get();
}
}
public class ProdCon {
public static void main(String args[]) {
Queue q = new Queue();
new Consumer(q);
new Producer(q);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment