1 30 package com.genimen.djeneric.ui; 31 32 import javax.swing.SwingUtilities ; 33 34 40 public abstract class DjSwingWorker 41 { 42 private Object value; 44 48 private static class ThreadVar 49 { 50 private Thread thread; 51 52 ThreadVar(Thread t) 53 { 54 thread = t; 55 } 56 57 synchronized Thread get() 58 { 59 return thread; 60 } 61 62 synchronized void clear() 63 { 64 thread = null; 65 } 66 } 67 68 private ThreadVar threadVar; 69 70 74 protected synchronized Object getValue() 75 { 76 return value; 77 } 78 79 82 private synchronized void setValue(Object x) 83 { 84 value = x; 85 } 86 87 90 public abstract Object construct(); 91 92 96 public void finished() 97 { 98 } 99 100 104 public void interrupt() 105 { 106 Thread t = threadVar.get(); 107 if (t != null) 108 { 109 t.interrupt(); 110 } 111 threadVar.clear(); 112 } 113 114 121 public Object get() 122 { 123 while (true) 124 { 125 Thread t = threadVar.get(); 126 if (t == null) 127 { 128 return getValue(); 129 } 130 try 131 { 132 t.join(); 133 } 134 catch (InterruptedException e) 135 { 136 Thread.currentThread().interrupt(); return null; 138 } 139 } 140 } 141 142 146 public DjSwingWorker() 147 { 148 final Runnable doFinished = new Runnable () 149 { 150 public void run() 151 { 152 finished(); 153 } 154 }; 155 156 Runnable doConstruct = new Runnable () 157 { 158 public void run() 159 { 160 try 161 { 162 setValue(construct()); 163 } 164 finally 165 { 166 threadVar.clear(); 167 } 168 169 SwingUtilities.invokeLater(doFinished); 170 } 171 }; 172 173 Thread t = new Thread (doConstruct); 174 threadVar = new ThreadVar(t); 175 } 176 177 180 public void start() 181 { 182 Thread t = threadVar.get(); 183 if (t != null) 184 { 185 t.start(); 186 } 187 } 188 } | Popular Tags |