1 11 12 package org.jivesoftware.messenger.launcher; 13 14 import javax.swing.SwingUtilities ; 15 16 20 public abstract class SwingWorker { 21 private Object value; private Thread thread; 23 24 28 private static class ThreadVar { 29 private Thread thread; 30 31 ThreadVar(Thread t) { 32 thread = t; 33 } 34 35 synchronized Thread get() { 36 return thread; 37 } 38 39 synchronized void clear() { 40 thread = null; 41 } 42 } 43 44 private ThreadVar threadVar; 45 46 50 protected synchronized Object getValue() { 51 return value; 52 } 53 54 57 private synchronized void setValue(Object x) { 58 value = x; 59 } 60 61 64 public abstract Object construct(); 65 66 70 public void finished() { 71 72 } 73 74 78 public void interrupt() { 79 Thread t = threadVar.get(); 80 if (t != null) { 81 t.interrupt(); 82 } 83 threadVar.clear(); 84 } 85 86 87 94 public Object get() { 95 while (true) { 96 Thread t = threadVar.get(); 97 if (t == null) { 98 return getValue(); 99 } 100 try { 101 t.join(); 102 } 103 catch (InterruptedException e) { 104 Thread.currentThread().interrupt(); return null; 106 } 107 } 108 } 109 110 111 115 public SwingWorker() { 116 final Runnable doFinished = new Runnable () { 117 public void run() { 118 finished(); 119 } 120 }; 121 122 Runnable doConstruct = new Runnable () { 123 public void run() { 124 try { 125 setValue(construct()); 126 } 127 finally { 128 threadVar.clear(); 129 } 130 SwingUtilities.invokeLater(new Runnable () { 131 public void run() { 132 finished(); 133 } 134 }); 135 136 } 137 }; 138 139 Thread t = new Thread (doConstruct); 140 threadVar = new ThreadVar(t); 141 } 142 143 146 public void start() { 147 Thread t = threadVar.get(); 148 if (t != null) { 149 t.start(); 150 } 151 } 152 153 154 } 155 156 | Popular Tags |