1 11 12 package EDU.oswego.cs.dl.util.concurrent.misc; 13 14 import java.lang.reflect.InvocationTargetException ; 15 import javax.swing.SwingUtilities ; 16 17 import EDU.oswego.cs.dl.util.concurrent.*; 18 19 115 public abstract class SwingWorker extends ThreadFactoryUser 116 implements Runnable { 117 118 119 private static final ThreadFactory FACTORY = new ThreadFactory() { 120 public Thread newThread(Runnable command) { 121 Thread t = new Thread (command); 122 t.setPriority(Thread.MIN_PRIORITY+1); 123 return t; 124 } 125 }; 126 127 128 private final FutureResult result = new FutureResult(); 129 130 131 private final long timeout; 132 133 134 private Thread thread; 135 136 137 public SwingWorker() { 138 this(FACTORY, 0); 139 } 140 141 146 public SwingWorker(long msecs) { 147 this(FACTORY, msecs); 148 } 149 150 156 protected SwingWorker(ThreadFactory factory, long msecs) { 157 setThreadFactory(factory); 158 if (msecs < 0) { 159 throw new IllegalArgumentException ("timeout="+msecs); 160 } 161 timeout = msecs; 162 } 163 164 167 protected abstract Object construct() throws Exception ; 168 169 173 protected void finished() { } 174 175 180 public long getTimeout() { 181 return timeout; 182 } 183 184 189 public void run() { 190 191 Callable function = new Callable() { 192 public Object call() throws Exception { 193 return construct(); 194 } 195 }; 196 197 Runnable doFinished = new Runnable () { 198 public void run() { 199 finished(); 200 } 201 }; 202 203 204 long msecs = getTimeout(); 205 if (msecs != 0) { 206 TimedCallable tc = new TimedCallable(function, msecs); 207 tc.setThreadFactory(getThreadFactory()); 208 function = tc; 209 } 210 211 result.setter(function).run(); 212 SwingUtilities.invokeLater(doFinished); 213 } 214 215 218 public synchronized void start() { 219 if (thread == null) { 220 thread = getThreadFactory().newThread(this); 221 } 222 thread.start(); 223 } 224 225 228 public synchronized void interrupt() { 229 if (thread != null) { 230 233 try { thread.interrupt(); } catch (Exception ex) { } 234 } 235 result.setException(new InterruptedException ()); 236 } 237 238 247 public Object get() 248 throws InterruptedException , InvocationTargetException { 249 return result.get(); 250 } 251 252 260 public Object timedGet(long msecs) 261 throws TimeoutException, InterruptedException , InvocationTargetException { 262 return result.timedGet(msecs); 263 } 264 265 272 public InvocationTargetException getException() { 273 return result.getException(); 274 } 275 276 282 public boolean isReady() { 283 return result.isReady(); 284 } 285 286 } 287 | Popular Tags |