?? 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 + -