[英]What is the correct way to make a thread return a value?
I'm new to Java threads and after testing to see how they work, I can't figure out how to make them do calculations and return the result the way I want.我是 Java 线程的新手,在测试它们如何工作之后,我不知道如何让它们进行计算并以我想要的方式返回结果。
For example, in my current program, I want my thread to query a database by calling a method that returns the data in a Vector
object when I click a JButton
.例如,在我当前的程序中,我希望我的线程通过调用一个方法来查询数据库,该方法在我单击JButton
时返回Vector
object 中的数据。 Then, with that vector object, I want to add each index (an array) as a row in a JTable
.然后,使用该向量 object,我想将每个索引(数组)作为一行添加到JTable
中。
What would be the correct way to accomplish this?实现这一目标的正确方法是什么? I know I could use a setter on my JTable
in the calling class but I'm sure there has to be a more "correct" way.我知道我可以在调用 class 的JTable
上使用二传手,但我确信必须有一个更“正确”的方式。
Yes, use a SwingWorker
.是的,使用SwingWorker
。 This mechanism 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.此机制设计用于需要在后台线程中运行长时间运行的任务并在完成时或在处理时向 UI 提供更新的情况。 Since Swing is single-threaded, this allows the UI to remain responsive .由于 Swing 是单线程的,这允许 UI 保持响应。
or basic workaround by impements Runnable where output to the GUI must be wrapped into invokeLater more about in Concurrency in Swing或通过 impements Runnable的基本解决方法,其中 output 到 GUI 必须包装到invokeLater更多关于 并发在 Swing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.