Guest User

Untitled

a guest
Oct 23rd, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. import java.util.concurrent.*;
  2. class WorkQueue{
  3. public static void main (String[] args){
  4. int capacity = n;
  5. ExecutorService executor = new ExecutorService (new FixedThreadPool(n)); //CachedThreadPool is another alternative with the caveat that when all threads are busy, new threads are spawned
  6. BlockingQueue queue = new ArrayBlockingQueue (100);// Some analysis will have to be done to understand how many messages will be placed in the
  7. //queue by the producers. For now it's an arbitrary 100.
  8. for int(i = 0; i < numOfProducers; i++){
  9. executor.submit(new Producer(queue, "Hello"));
  10. }
  11. Future result = executor.submit(new Consumer(queue));//consumer reads from the queue
  12.  
  13.  
  14. class Producer implements Runnable{
  15. private final BlockingQueue queue;
  16. private String message;
  17. //constructur
  18. Public Producer(BlockingQueue queue, String message){
  19. this.queue = queue;
  20. this.message = message;
  21. }
  22.  
  23. @override
  24. public void run(){//add try catch block as necessary
  25. queue.put(message);
  26. }
  27. }
  28.  
  29. Class Consumer implements Callable{// Because I'll get a future based on this
  30. private final BlockingQueue queue;
  31. public Consumer(BlockingQueue queue){
  32. this.queue = queue;
  33. }
  34. @override
  35. public String call (){
  36. String message = queue.take();
  37. return "Success";
  38. }
  39. }
  40. }
Add Comment
Please, Sign In to add comment