1 33 34 package edu.rice.cs.util.swing; 35 36 import javax.swing.SwingUtilities ; 37 38 54 public abstract class SwingWorker { 55 private volatile Object _value; 58 62 private static class ThreadVar { 63 private volatile Thread _thread; 64 ThreadVar(Thread t) { _thread = t; } 65 Thread get() { return _thread; } 66 void clear() { _thread = null; } 67 } 68 69 private volatile ThreadVar _threadVar; 70 71 74 protected Object getValue() { return _value; } 75 76 77 private void setValue(Object x) { _value = x; } 78 79 80 public abstract Object construct(); 81 82 85 public void finished() { } 86 87 88 public void interrupt() { 89 Thread t = _threadVar.get(); 90 if (t != null) t.interrupt(); 91 _threadVar.clear(); 92 } 93 94 99 public Object get() { 100 while (true) { 101 Thread t = _threadVar.get(); 102 if (t == null) return getValue(); 103 try { t.join(); } 104 catch (InterruptedException e) { 105 Thread.currentThread().interrupt(); return null; 107 } 108 } 109 } 110 111 112 public SwingWorker() { 113 final Runnable doFinished = new Runnable () { 114 public void run() { finished(); } 115 }; 116 117 Runnable doConstruct = new Runnable () { 118 public void run() { 119 try { setValue(construct()); } 120 catch (final RuntimeException e) { 121 SwingUtilities.invokeLater(new Runnable () { public void run() { throw e; } }); 123 throw e; 124 } 125 catch (final Error e) { 126 SwingUtilities.invokeLater(new Runnable () { public void run() { throw e; } }); 128 throw e; 129 } 130 finally { _threadVar.clear(); } 131 132 SwingUtilities.invokeLater(doFinished); 133 } 134 }; 135 136 Thread t = new Thread (doConstruct); 137 _threadVar = new ThreadVar(t); 138 } 139 140 141 public void start() { 142 Thread t = _threadVar.get(); 143 if (t != null) t.start(); 144 } 145 } 146 | Popular Tags |