Facebook
From Queen Wolf, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 84
  1. //Java implementation of a producer and consumer
  2. //that use semaphores to control synchronization
  3. import java.util.concurrent.Semaphore;
  4. class Queue {
  5. // an item
  6. int item;
  7. // semCon initialized with 0 permits
  8. // to ensure put() executes first
  9. static Semaphore semCon = new Semaphore(0);
  10. static Semaphore semProd = new Semaphore(1);
  11.  
  12. //to get an item from buffer
  13. void get() {
  14. try {
  15. // Before consumer can consume an item,
  16. // it must acquire a permit from semCon
  17. semCon.acquire();
  18. }
  19. catch(InterruptedException e) {
  20. System.out.println("InterruptedException caught");
  21. }
  22.  
  23. //consumer consuming an item
  24. System.out.println("Consumer consumed item : " + item);
  25. // After consumer consumes the item,
  26. // it releases semProd to notify producer
  27. semProd.release();
  28. }
  29.  
  30. //to put an item in buffer
  31. void put(int item) {
  32. try {
  33. // Before producer can produce an item,
  34. // it must acquire a permit from semProd
  35. semProd.acquire();
  36. } catch(InterruptedException e) {
  37. System.out.println("InterruptedException caught");
  38. }
  39. //producer producing an item
  40. this.item = item;
  41. System.out.println("Producer produced item : " + item);
  42. // After producer produces the item,
  43. // it releases semCon to notify consumer
  44. semCon.release();
  45. }
  46. }