简体   繁体   English

使线程返回值的正确方法是什么?

[英]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.

相关问题 使用退货的正确方法是什么? - What is the correct way to use return? 在某些情况下终止线程的正确方法是什么? - What is the correct way to terminate thread on some condition? 将数据传递到正在运行的线程的正确方法是什么 - What is the correct way to pass data to a running thread 在Spring中返回列表的正确方法是什么 - What is the correct way of return a List in Spring 在线程池执行器中从Runnables返回值的最简单,最有效的方法是什么? - what is the most simple and efficient way to return value from Runnables in Thread Pool Executor? 这是在静态方法中使单例映射线程安全的正确有效方法吗? - Is this the correct and efficient way to make a singleton map thread safe in a static method 停止线程等待网络活动的正确方法是什么? - What is the correct way to stop a thread waiting for network activity? 进行while循环的正确方法是什么? 我的方式不起作用 - What is the correct way to make a while loop?? my way is not working 从插入函数中返回布尔值的正确方法是什么? - What is the correct way to return booleans from something like an insert function? 从对象返回嵌套集合的正确方法是什么? - What is the correct way to return a nested collection from a object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM