简体   繁体   English

Java SwingWorker - 使用发布/进程更新 EDT 中的 TextArea?

[英]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 Socket Server).我刚刚编写了一个启动 SwingWorker(运行 Socket 服务器)的 Swing 程序。 I have a JTextArea on the Swing GUI which gets updated with the data received by the Socket Server, using a JTextArea.append(String).我在 Swing GUI 上有一个 JTextArea,它使用 JTextArea.append(String) 使用 Socket 服务器接收的数据进行更新。

Is it the correct/threadsafe way to update a JTextArea on the Swing GUI?在 Swing GUI 上更新 JTextArea 是否正确/线程安全? 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). SwingWorker 通常用于一次长时间运行的进程(任何需要超过几毫秒才能完成的进程)。 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如果您有持久连接,则更适合使用专用的 ExecutorService 来运行该进程,然后当您要更新 swing 组件调用时

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原因是 SwingWorkers 使用固定的线程池大小,因此如果您有一个永远不会完成的进程,它会限制其他 SwingWorkers 可以同时使用的线程数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM