Advertisement
benaryorg

Java AsyncPrinter

Aug 19th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class AsyncPrinter extends Thread
  4. {
  5. private Queue<String> queue;
  6.  
  7. public AsyncPrinter()
  8. {
  9. this.queue=new LinkedList<>();
  10. this.setDaemon(true);
  11. this.start();
  12. }
  13.  
  14. public void run()
  15. {
  16. String name;
  17. while(true)
  18. {
  19. while((name=this.queue.poll())!=null)
  20. {
  21. System.out.print("Hello, ");
  22. System.out.println(name);
  23. }
  24. try
  25. {
  26. this.wait();
  27. }
  28. catch(Exception ex)
  29. {
  30. }
  31. }
  32. }
  33.  
  34. public boolean add(String name)
  35. {
  36. boolean ret=queue.offer(name);
  37. try
  38. {
  39. this.notifyAll();
  40. }
  41. catch(IllegalMonitorStateException ex)
  42. {
  43. }
  44. return ret;
  45. }
  46.  
  47. public static void main(String... args)
  48. {
  49. AsyncPrinter printer=new AsyncPrinter();
  50. printer.add("test");
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement