00001 package guiUtilities;
00002 import javax.swing.SwingUtilities;
00003
00016 public abstract class SwingWorker {
00017 private Object value;
00018
00023 private static class ThreadVar {
00024 private Thread thread;
00025 ThreadVar(Thread t) { thread = t; }
00026 synchronized Thread get() { return thread; }
00027 synchronized void clear() { thread = null; }
00028 }
00029
00030 private ThreadVar threadVar;
00031
00036 protected synchronized Object getValue() {
00037 return value;
00038 }
00039
00043 private synchronized void setValue(Object x) {
00044 value = x;
00045 }
00046
00050 public abstract Object construct();
00051
00056 public void finished() {
00057 }
00058
00063 public void interrupt() {
00064 Thread t = threadVar.get();
00065 if (t != null) {
00066 t.interrupt();
00067 }
00068 threadVar.clear();
00069 }
00070
00078 public Object get() {
00079 while (true) {
00080 Thread t = threadVar.get();
00081 if (t == null) {
00082 return getValue();
00083 }
00084 try {
00085 t.join();
00086 }
00087 catch (InterruptedException e) {
00088 Thread.currentThread().interrupt();
00089 return null;
00090 }
00091 }
00092 }
00093
00094
00099 public SwingWorker() {
00100 final Runnable doFinished = new Runnable() {
00101 public void run() { finished(); }
00102 };
00103
00104 Runnable doConstruct = new Runnable() {
00105 public void run() {
00106 try {
00107 setValue(construct());
00108 }
00109 finally {
00110 threadVar.clear();
00111 }
00112
00113 SwingUtilities.invokeLater(doFinished);
00114 }
00115 };
00116
00117 Thread t = new Thread(doConstruct);
00118 threadVar = new ThreadVar(t);
00119 }
00120
00124 public void start() {
00125 Thread t = threadVar.get();
00126 if (t != null) {
00127 t.start();
00128 }
00129 }
00130 }