Friday, 8 April 2016

How to solve a Producer Consumer problem using BlockingQueue ?


Example

public class Producer implements Runnable {
  private final BlockingQueue<File> queue;



  
  Producer(BlockingQueue<File> queue) {
      this.queue = queue;
  }

  public void run() {
    try {
       while(condition) {
          queue.put(file);
       }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

public class Consumer implements Runnable {
  private final BlockingQueue<File> queue;

  public Consumer(BlockingQueue<File> queue) {
    this.queue = queue;
  }


  public void run() {
    try {
       while(condition) {
          processFile(queue.take());
       }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
  }
}



Client code
while (condition) {
   new Thread(new Producer(queue)).start();
}

 
while (condition) {
   new Thread(new Consumer(queue)).start();

}

Note : It' s not a complete program but a prototype

No comments:

Post a Comment

Note: only a member of this blog may post a comment.