Linkedin Interview Question
Team: systems and infrastructure
Country: United States
Interview Type: Phone Interview
Here is the solution:-
public class ProducerConsumerProblem {
private BlockingQueue<String> items = new LinkedBlockingQueue<String>(5);
private Scanner scanner = new Scanner(System.in);
public ProducerConsumerProblem() {
consume();
produce();
}
public void produce(){
Runnable runnable = new Runnable() {
@Override
public void run() {
while(true){
System.out.print("Name the new Item - ");
try {
items.put(scanner.next());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(runnable);
t.start();
}
public void consume(){
Runnable runnable = new Runnable() {
@Override
public void run() {
while(true){
try {
System.out.print("Retrieving the item - "+items.take());
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(runnable);
t.start();
}
public static void main(String[] args) {
new ProducerConsumerProblem();
}
}
Using java synchronized, both deque and enque has to ensure operations are vaild or else wait.
wait until space available for dequing then notifying waiting threads.
public class BlockingQueue {
private List queue = new LinkedList();
private int limit = 10;
public BlockingQueue(int limit){
this.limit = limit;
}
public synchronized void enqueue(Object item)
throws InterruptedException {
while(this.queue.size() == this.limit) {
wait();
}
this.queue.add(item);
notifyAll();
}
public synchronized Object dequeue()
throws InterruptedException{
while(this.queue.size() == 0){
wait();
}
Object obj = this.queue.remove(0);
notifyAll();
}
}
Implementation using semaphores
- Looper October 11, 2012