1 package org.openharmonise.swing; 2 3 import javax.swing.SwingUtilities ; 4 5 17 public abstract class SwingWorker { 18 private Object value; 19 20 24 private static class ThreadVar { 25 private Thread thread; 26 ThreadVar(Thread t) { thread = t; } 27 synchronized Thread get() { return thread; } 28 synchronized void clear() { thread = null; } 29 } 30 31 private ThreadVar threadVar; 32 33 37 protected synchronized Object getValue() { 38 return value; 39 } 40 41 44 private synchronized void setValue(Object x) { 45 value = x; 46 } 47 48 51 public abstract Object construct(); 52 53 57 public void finished() { 58 } 59 60 64 public void interrupt() { 65 Thread t = threadVar.get(); 66 if (t != null) { 67 t.interrupt(); 68 } 69 threadVar.clear(); 70 } 71 72 79 public Object get() { 80 while (true) { 81 Thread t = threadVar.get(); 82 if (t == null) { 83 return getValue(); 84 } 85 try { 86 t.join(); 87 } 88 catch (InterruptedException e) { 89 Thread.currentThread().interrupt(); return null; 91 } 92 } 93 } 94 95 96 100 public SwingWorker() { 101 final Runnable doFinished = new Runnable () { 102 public void run() { finished(); } 103 }; 104 105 Runnable doConstruct = new Runnable () { 106 public void run() { 107 try { 108 setValue(construct()); 109 } 110 finally { 111 threadVar.clear(); 112 } 113 114 SwingUtilities.invokeLater(doFinished); 115 } 116 }; 117 118 Thread t = new Thread (doConstruct); 119 threadVar = new ThreadVar(t); 120 } 121 122 125 public void start() { 126 Thread t = threadVar.get(); 127 if (t != null) { 128 t.start(); 129 } 130 } 131 } 132 | Popular Tags |