Attempt to modify the interface element in a thread other than the thread that created the SWT interface will throw the following exception
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)
The preceding thread-0 is another enabled thread.
【Analysis]:
In the SWT program,
SWT automatically creates a user interface thread
Non-User Interface threads cannot directly operate on User Interface threads
To try to modify the user interface in another thread, use the following method:
If (! This. display. isdisposed ()){
Runnable = new runnable (){
Public void run (){
// Modify the interface code
}
};
Display. syncexec (runnable); // The key lies in this sentence.
}
Description in SWT-DOC:
public void syncExec(java.lang.Runnable runnable)
-
Causes
run()
Method of the runnable to be invoked
The user-interface threadAt the next reasonable opportunity. The thread which callthis method is suincluded until the runnable completes.
-
-
Parameters:
-
runnable
-Code to run on the user-interface thread.
In addition, it corresponds to another method:
public void asyncExec(java.lang.Runnable runnable)
-
Causes
run()
Method of the runnable to be invoked
The user-interface threadAt 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.