| 1 31 32 package org.antlr.works.ate.syntax.misc; 33 34 public abstract class ATEThread implements Runnable { 35 36 protected int threadSleep = 100; 37 protected int threshold = 0; 38 protected int default_threshold = 250; 39 protected boolean running = false; 40 protected boolean run = false; 41 protected Thread thread = null; 42 protected boolean asleep = false; 43 protected boolean skip = false; 44 45 public ATEThread() { 46 } 47 48 public void setDefaultThreshold(int threshold) { 49 this.default_threshold = threshold; 50 } 51 52 public synchronized void setRunning(boolean flag) { 53 running = flag; 54 } 55 56 public synchronized boolean isRunning() { 57 return running; 58 } 59 60 protected synchronized void start() { 61 this.threadSleep = Integer.MAX_VALUE; 62 start_(); 63 } 64 65 protected synchronized void start(int threadSleep) { 66 this.threadSleep = threadSleep; 67 start_(); 68 } 69 70 private void start_() { 71 if(!run) { 72 run = true; 73 thread = new Thread (this); 74 thread.setName(getClass().toString()); 75 thread.start(); 76 } 77 } 78 79 public synchronized void skip() { 80 skip = true; 81 } 82 83 private synchronized void resetSkip() { 84 skip = false; 85 } 86 87 public synchronized void stop() { 88 threshold = 0; 89 run = false; 90 thread.interrupt(); 91 } 92 93 97 public synchronized void awakeThread() { 98 awakeThread(default_threshold); 99 } 100 101 public synchronized void awakeThread(int threshold) { 102 resetSkip(); 103 this.threshold = threshold; 104 if(asleep) 105 thread.interrupt(); 106 } 107 108 public boolean cancel() { 109 return !run; 110 } 111 112 protected abstract void threadRun() throws Exception ; 113 114 public void threadReportException(Exception e) { 115 e.printStackTrace(); 116 } 117 118 public boolean threadSleep(int ms) { 119 boolean interrupted = false; 120 asleep = true; 121 try { 122 Thread.sleep(ms); 123 } catch (InterruptedException e) { 124 interrupted = true; 125 } 126 asleep = false; 127 return interrupted; 128 } 129 130 public void run() { 131 setRunning(true); 132 while(run) { 133 if(threadSleep(threadSleep)) { 134 if(threshold>0) { 138 while(threadSleep(threshold)) { 139 } 140 } 141 } 142 143 if(!run) 144 break; 145 146 if(skip) { 147 resetSkip(); 148 continue; 149 } 150 151 try { 152 threadRun(); 153 } catch(Exception e) { 154 threadReportException(e); 155 } 156 } 157 setRunning(false); 158 } 159 160 } 161 | Popular Tags |