gpt4 book ai didi

java - 为什么选择 SwingWorker?为什么不只是 Thread 或 Runnable?

转载 作者:太空狗 更新时间:2023-10-29 22:48:59 25 4
gpt4 key购买 nike

使用 SwingWorker 代替 ThreadRunnable 有什么优势?

最佳答案

我认为 SwingWorker 的文档还不错:

An abstract class to perform lengthy GUI-interacting tasks in a dedicated thread.

When writing a multi-threaded application using Swing, there are two constraints to keep in mind: (refer to How to Use Threads for more details):

  • Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
  • Swing components should be accessed on the Event Dispatch Thread only.

These constraints mean that a GUI application with time intensive computing needs at least two threads: 1) a thread to perform the lengthy task and 2) the Event Dispatch Thread (EDT) for all GUI-related activities. This involves inter-thread communication which can be tricky to implement.

SwingWorker is designed for situations where you need to have a long running task run in a background thread and provide updates to the UI either when done, or while processing. Subclasses of SwingWorker must implement the doInBackground() method to perform the background computation.

当然,您可以使用 Thread、Runtime 和 SwingUtilities (invokeLater) 来完成此操作,但使用 SwingWorker 类更容易并且可能更不容易出错。

关于java - 为什么选择 SwingWorker?为什么不只是 Thread 或 Runnable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4518534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com