📄 swingworker.java
字号:
import javax.swing.SwingUtilities;
// 这是第三版本的SwingWorker,由抽象类的子类执行在线程中的相关类的GUI工作有关
// 这个类的用法请参阅:
// http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
// 注意:在第三版本中API 稍微有点变化。在创建SwingWorker类之后,必须马上在该类
// 上调用start()方法。
public abstract class SwingWorker {
private Object value; // see getValue(), setValue()
private Thread thread;
// 在独立的同步控制下,维护引用当前工作线程的类。
private static class ThreadVar {
private Thread thread;
ThreadVar(Thread t) { thread = t; }
synchronized Thread get() { return thread; }
synchronized void clear() { thread = null; }
}
private ThreadVar threadVar;
// 如果工作线程没有置为null的话,就获得工作线程作产生的值。
protected synchronized Object getValue() {
return value;
}
// 设定工作线程所产生的值。
private synchronized void setValue(Object x) {
value = x;
}
// 用 <code>get</code> 方法返回计算的值。
public abstract Object construct();
// 在<code>construct</code>方法已经返回后,调用事件发送线程(不是工作线程)。
public void finished() {
}
// 一个新的中断工作线程方法。调用这个方法以强迫工作线程终止工作。
public void interrupt() {
Thread t = threadVar.get();
if (t != null) {
t.interrupt();
}
threadVar.clear();
}
// 返回用<code>construct</code>方法创建的值。如果既不是构造方法线程又不是
// 在产生值之前中断了的当前线程,则返回null。
public Object get() {
while (true) {
Thread t = threadVar.get();
if (t == null) {
return getValue();
}
try {
t.join();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
// 用调用<code>construct</code>方法启动一个线程,然后再退出。
public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() { finished(); }
};
Runnable doConstruct = new Runnable() {
public void run() {
try {
setValue(construct());
}
finally {
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
// 启动工作线程
public void start() {
Thread t = threadVar.get();
if (t != null) {
t.start();
}
}
public java.lang.Thread getThread() {
return threadVar.get();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -