Java SwingWorker - using publish/process to update a TextArea in EDT?
I had just coded a Swing program that starts up a SwingWorker (which runs a Socke开发者_运维百科t Server). I have a JTextArea on the Swing GUI which gets updated with the data received by the Socket Server, using a JTextArea.append(String).
Is it the correct/threadsafe way to update a JTextArea on the Swing GUI? What about using publish/process?
SwingWorker is usually used for one time long running processes (anything that will take more than a few milliseconds to complete). If you have persistent connection, it would be more appropriate to use a dedicated ExecutorService which will run the process, then when you want to update a swing component call
SwingUtilities.invokeLater(new Runnable() {
public void run() {
.. update here
}
}
The reason for this is SwingWorkers use a fixed thread pool size, so if you have a process that never completes than it limits the number threads other SwingWorkers can use concurrently
精彩评论