clojure 中的 SwingWorker 执行

发布于 2024-12-28 19:43:15 字数 93 浏览 0 评论 0原文

在 clojure 中,您可以创建 SwingWorker 代理并实现 doInBackground 和 do 方法。您将如何继续调用 Swingworker 的执行方法?

In clojure you can create a SwingWorker proxy and implement doInBackground and do methods. How would you go on to invoke execute method of swingworker?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回心转意 2025-01-04 19:43:15

您可以使用标准 Java 互操作创建和调用 SwingWorker,例如:

;; define a proxy that extends SwingWorker
(def my-swing-worker 
  (proxy [SwingWorker] []
    (doInBackground []
      (reduce + (range 1000000)))))

;; run the SwingWorker
(.execute my-swing-worker)

;; Get the result
(.get my-swing-worker)
=> 499999500000

但是,通常在 Clojure 中您不会直接使用 SwingWorkers。 Clojure 中已经有一个功能可以提供 SwingWorker 的功能:future 使用单独的线程来计算长时间运行的任务,并允许您稍后获取结果。用法示例:

;; define and launch a future
(def my-future 
  (future 
    (reduce + (range 1000000))))

;; get the result (will wait for future to complete if needed)
@my-future
=> 499999500000

我认为大多数人都会同意“纯 Clojure”方式对于运行后台任务来说更简单、更惯用。我能想到更喜欢 SwingWorker 的唯一原因是,如果您正在使用它提供的一些特定 GUI 集成功能(例如,触发属性更改事件的能力)。

You can create and invoke a SwingWorker using standard Java interop, e.g.:

;; define a proxy that extends SwingWorker
(def my-swing-worker 
  (proxy [SwingWorker] []
    (doInBackground []
      (reduce + (range 1000000)))))

;; run the SwingWorker
(.execute my-swing-worker)

;; Get the result
(.get my-swing-worker)
=> 499999500000

However, normally in Clojure you wouldn't use SwingWorkers directly. There is already a feature in Clojure that provides the functionaility of a SwingWorker: a future uses a separate thread to calculate a long running task and allows you to get the result later. Example usage:

;; define and launch a future
(def my-future 
  (future 
    (reduce + (range 1000000))))

;; get the result (will wait for future to complete if needed)
@my-future
=> 499999500000

I think most people would agree the "pure Clojure" way is simpler and more idiomatic for running background tasks. The only reason I can think of to prefer SwingWorker is if you are using some of the specific GUI integration features it provides (e.g. the ability to fire property change events).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文