1 7 8 package org.jdesktop.swing.utils; 9 10 import javax.swing.SwingUtilities ; 11 12 24 public abstract class SwingWorker { 25 private Object value; private Thread thread; 27 28 32 private static class ThreadVar { 33 private Thread thread; 34 ThreadVar(Thread t) { thread = t; } 35 synchronized Thread get() { return thread; } 36 synchronized void clear() { thread = null; } 37 } 38 39 private ThreadVar threadVar; 40 41 45 protected synchronized Object getValue() { 46 return value; 47 } 48 49 52 private synchronized void setValue(Object x) { 53 value = x; 54 } 55 56 59 public abstract Object construct(); 60 61 65 public void finished() { 66 } 67 68 72 public void interrupt() { 73 Thread t = threadVar.get(); 74 if (t != null) { 75 t.interrupt(); 76 } 77 threadVar.clear(); 78 } 79 80 87 public Object get() { 88 while (true) { 89 Thread t = threadVar.get(); 90 if (t == null) { 91 return getValue(); 92 } 93 try { 94 t.join(); 95 } 96 catch (InterruptedException e) { 97 Thread.currentThread().interrupt(); return null; 99 } 100 } 101 } 102 103 104 108 public SwingWorker() { 109 final Runnable doFinished = new Runnable () { 110 public void run() { finished(); } 111 }; 112 113 Runnable doConstruct = new Runnable () { 114 public void run() { 115 try { 116 setValue(construct()); 117 } 118 finally { 119 threadVar.clear(); 120 } 121 122 SwingUtilities.invokeLater(doFinished); 123 } 124 }; 125 126 Thread t = new Thread (doConstruct); 127 threadVar = new ThreadVar(t); 128 } 129 130 133 public void start() { 134 Thread t = threadVar.get(); 135 if (t != null) { 136 t.start(); 137 } 138 } 139 } 140 | Popular Tags |