Advertisement
yerzhik

thread pause

Mar 26th, 2014
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. class Data {
  2.     private static int value = 0;
  3.     public static synchronized int getValue() {
  4.         return value;
  5.     }
  6.    
  7.     public static synchronized void setValue(int value) {
  8.         this.value = value;
  9.     }
  10. }
  11.  
  12. class Simulator extends Thread {
  13.     private void waitIfNotAllowed() {
  14.                 if (Data.getValue() == 1) {
  15.                     Data.setValue(2);
  16.                     while (Data.getValue() != 0) {
  17.                         sleep(3000);
  18.                     }
  19.                 }
  20.     }
  21.    
  22.     public void run() {
  23.         try {
  24.             while (true) {
  25.                 waitIfNotAllowed();            
  26.                 doSomething();
  27.             }
  28.         } catch(Exception ex) {
  29.             LOG.error(null, ex);
  30.         }
  31.     }      
  32. }
  33.  
  34. class Scheduler extends Thread {
  35.     private void pauseThread() {
  36.         Data.setValue(1);
  37.        
  38.         while (Data.getValue() != 2) {
  39.             sleep(3000);
  40.         }
  41.     }
  42.    
  43.     private void continueThread() {
  44.         Data.setValue(0);
  45.     }
  46.    
  47.     public void run() {
  48.         try {
  49.             while (true) {
  50.                 doSomething();
  51.                 if (...) {
  52.                     pauseThread();
  53.                     doSpecialThing();
  54.                     continueThread();
  55.                 }              
  56.                 doSomething();
  57.             }
  58.         } catch(Exception ex) {
  59.             LOG.error(null, ex);
  60.         }
  61.     }      
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement