防止 GUI 冻结并有按钮取消操作/杀死线程 [英] prevent GUI from freezing and have button to cancel operation/kill thread

查看:54
本文介绍了防止 GUI 冻结并有按钮取消操作/杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:

我有一个 JFrame 包含一个 JTextArea 显示正在进行的连接上的更新.如果用户想取消连接,他们应该能够按下它右侧的 JButton.但是,由于连接在尝试连接时阻塞(使用)线程,因此 GUI 会冻结.我正在寻找快速修复.可能将 ActionListener 放在单独的线程上?尽管我可以基本使用可运行对象,但我对线程没有太多经验.

I have a JFrame containing a JTextArea displaying updates on an on going connection. The user is supposed to be able to press the JButton to the right of it if they want to cancel the connection. However, since the connection is blocking (using) the thread while trying to connect, the GUI becomes frozen. I am looking for a quick fix. Having the ActionListener on a separate thread possibly? I do not have much experience with threads though I can make basic use of runnables.

答案是否与使用 EDT 有关?如果是这样,应该如何实施?

Does the answer have something to do with using the EDT? If so how should this be implemented?

PS 澄清一下,按钮应该能够杀死创建连接的线程.阅读后似乎是一个 executorService.可以帮忙吗?是的?还是根本没有?

PS for clarification, the button should be able to kill a thread creating the connection. After reading it seems that an executorService. could help with this? Yes? or not at all?

推荐答案

建议首先了解 Swing(或几乎任何 UI 框架)和多线程的速度.这是餐巾纸版:

It would be advisable to first get up to speed regarding Swing (or virtually any UI framework) and multi-threading. This is the napkin version:

  • 对 UI 的任何修改或从中读取(例如获取文本字段的值)必须在 UI 线程(有时也称为Swing 线程"或事件调度线程"(EDT)
  • 任何阻塞或长时间运行的操作 - 如网络通信 - 不得在 UI 线程上运行.否则,它们将阻止按钮工作、更新文本等.
  • 在 Java 中,ExecutorService 和它的朋友可以相对容易地让长时间运行或阻塞的东西在后台线程上运行
  • 如果后台线程发生某些事情需要您更新 UI,请将 UI 相关代码封装在 EventQueue.invokeLater 调用中.这将确保您传递的 Runnable 在 UI 线程上执行.
  • Any modifications to the UI or reads from it (e. g. to get the value of a textfield) must be done only on the UI thread (which is also sometimes called the "Swing Thread" or "Event Dispatch Thread" (EDT)
  • Any blocking or long-running operations - like network communications - must NOT be run on the UI thread. Otherwise they will prevent buttons from working, texts from being updated etc.
  • In Java, the ExecutorService and its friends will make it relatively easy to let long-running or blocking stuff run on a background thread
  • If something happens on the background thread that requires you to update the UI, encapsulate the UI-related code in an EventQueue.invokeLater call. This will make sure the Runnable you pass gets executed on the UI thread.

SwingWorker 类封装了这个逻辑,并为更简单的情况提供了一个易于使用的帮助器.

The SwingWorker class encapsulates this logic and provides an easy to use helper for simpler cases.

第一次这样做时,可能有点令人生畏,但彻底理解这一点是值得的,因为它不仅适用于 Swing,也适用于任何其他 UI 代码.

When doing this the first time, it can be a bit daunting, but it pays off to understand this thoroughly, because it does not only apply to Swing, but to any other UI code, too.

这篇关于防止 GUI 冻结并有按钮取消操作/杀死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆