code_junkie

Java while loop and Threads!

Nov 13th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. volatile boolean stop = false;
  2.  
  3. Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
  4.  
  5. public void run()
  6. {
  7. stop = true;
  8. }
  9. });
  10.  
  11. boolean stop = false;
  12. final Object event = new Object();
  13.  
  14. Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
  15.  
  16. public void run()
  17. {
  18. synchronized(event)
  19. {
  20. stop = true;
  21. event.notifyAll();
  22. }
  23. }
  24. });
  25.  
  26. // ... and in your polling loop ...
  27. synchronized(event)
  28. {
  29. while(!stop)
  30. {
  31. // ... do JDBC access ...
  32. try
  33. {
  34. // wait 30 seconds, but break out as soon as the event is fired.
  35. event.wait(30000);
  36. }
  37. catch(InterruptedException e)
  38. {
  39. // Log a message and exit. Never ignore interrupted exception.
  40. break;
  41. }
  42. }
  43. }
  44.  
  45. public class Service implements Runnable {
  46.  
  47. private boolean shouldStop = false;
  48.  
  49. public synchronized stop() {
  50. shouldStop = true;
  51. notify();
  52. }
  53.  
  54. private synchronized shouldStop() {
  55. return shouldStop;
  56. }
  57.  
  58. public void run() {
  59. setUp();
  60. while (!shouldStop()) {
  61. doStuff();
  62. sleep(60 * 1000);
  63. }
  64. }
  65.  
  66. private synchronized sleep(long delay) {
  67. try {
  68. wait(delay);
  69. } catch (InterruptedException ie1) {
  70. /* ignore. */
  71. }
  72. }
  73.  
  74. }
Add Comment
Please, Sign In to add comment