1 import javax.swing.SwingUtilities ; 2 3 15 public abstract class SwingWorker { 16 private Object value; 18 22 private static class ThreadVar { 23 private Thread thread; 24 ThreadVar(Thread t) { thread = t; } 25 synchronized Thread get() { return thread; } 26 synchronized void clear() { thread = null; } 27 } 28 29 private ThreadVar threadVar; 30 31 35 protected synchronized Object getValue() { 36 return value; 37 } 38 39 42 private synchronized void setValue(Object x) { 43 value = x; 44 } 45 46 49 public abstract Object construct(); 50 51 55 public void finished() { 56 } 57 58 62 public void interrupt() { 63 Thread t = threadVar.get(); 64 if (t != null) { 65 t.interrupt(); 66 } 67 threadVar.clear(); 68 } 69 70 77 public Object get() { 78 while (true) { 79 Thread t = threadVar.get(); 80 if (t == null) { 81 return getValue(); 82 } 83 try { 84 t.join(); 85 } 86 catch (InterruptedException e) { 87 Thread.currentThread().interrupt(); return null; 89 } 90 } 91 } 92 93 94 98 public SwingWorker() { 99 final Runnable doFinished = new Runnable () { 100 public void run() { finished(); } 101 }; 102 103 Runnable doConstruct = new Runnable () { 104 public void run() { 105 try { 106 setValue(construct()); 107 } 108 finally { 109 threadVar.clear(); 110 } 111 112 SwingUtilities.invokeLater(doFinished); 113 } 114 }; 115 116 Thread t = new Thread (doConstruct); 117 threadVar = new ThreadVar(t); 118 } 119 120 123 public void start() { 124 Thread t = threadVar.get(); 125 if (t != null) { 126 t.start(); 127 } 128 } 129 } 130 | Popular Tags |