1. 程式人生 > 其它 >SWTException: Invalid thread access解決方法總結

SWTException: Invalid thread access解決方法總結

在建立SWT介面的執行緒之外的執行緒中嘗試去修改介面元素.將丟擲以下異常

Exception in thread “Thread-0” org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:2942)
at org.eclipse.swt.SWT.error(SWT.java:2865)
at org.eclipse.swt.SWT.error(SWT.java:2836)
上述Thread-0是另外開啟的一個執行緒.
【解析】:
在SWT程式中,SWT會自動建立一個使用者介面執行緒,非使用者介面執行緒不能直接操作使用者介面執行緒,要想在另外一個執行緒中嘗試修改使用者介面,應採用一下方法:

if (!this.display.isDisposed()) {
//首先建立一個單獨的執行緒用來修改介面元素
Runnable runnable = new Runnable() {
public void run() {
// 你改介面的程式碼
}
};
//通過syncExec方法來執行上一步建立的執行緒
display.syncExec(runnable);
}
swt-doc中的說明:
public void syncExec(java.lang.Runnable runnable)
Causes the run() method of the runnable to be invoked by the user-interface thread at the next reasonable opportunity. The thread which calls this method is suspended until the runnable completes.
Parameters:
runnable – code to run on the user-interface thread.
同步呼叫,需要等待主介面處理完成之後,才能繼續。
此外,與之對應的另一個方法:
public void asyncExec(java.lang.Runnable runnable)
Causes the run() method of the runnable to be invoked by the user-interface thread at the next reasonable opportunity. The caller of this method continues to run in parallel, and is not notified when the runnable has completed.
Parameters:
runnable – code to run on the user-interface thread.
非同步呼叫,不等待主介面執行緒處理結果。
[整理自網路]