Guest User

Untitled

a guest
Jun 19th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. public class MyObjHandler implements Runnable {
  2.  
  3. private final BlockingQueue<MyObj> queue;
  4.  
  5. public class MyObjHandler(BlockingQueue queue) {
  6. this.queue = queue;
  7. }
  8.  
  9. public void run() {
  10. try {
  11. while (true) {
  12. MyObj obj = queue.take();
  13. // process obj here
  14. // ...
  15. }
  16. } catch (InterruptedException e) {
  17. Thread.currentThread().interrupt();
  18. }
  19. }
  20. }
  21.  
  22. public void testHandler() {
  23.  
  24. BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100);
  25.  
  26. MyObjectHandler handler = new MyObjectHandler(queue);
  27. new Thread(handler).start();
  28.  
  29. // get objects for handler to process
  30. for (Iterator<MyObj> i = getMyObjIterator(); i.hasNext(); ) {
  31. queue.put(i.next());
  32. }
  33.  
  34. // what code should go here to tell the handler
  35. // to stop waiting for more objects?
  36. }
  37.  
  38. BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100);
  39. MyObjectHandler handler = new MyObjectHandler(queue);
  40. Thread thread = new Thread(handler);
  41. thread.start();
  42. for (Iterator<MyObj> i = getMyObjIterator(); i.hasNext(); ) {
  43. queue.put(i.next());
  44. }
  45. thread.interrupt();
  46.  
  47. thread.interrupt()
Add Comment
Please, Sign In to add comment