简体   繁体   English

在不冻结GUI的情况下用于小任务的线程的替代

[英]Alternative to thread for small tasks without freezing the GUI

I'm writing a small application, composed by a gui and a couple of buttons. 我正在编写一个由gui和几个按钮组成的小应用程序。 When the user clicks one of them, the program must download a webpage, do a couple of matching and return a value to the gui. 用户单击其中的一个时,程序必须下载一个网页,进行几次匹配,然后将值返回给gui。 The question is, I must start a new thread every time the user clicks on that button, or there's an alternative to threads for those kind of small tasks ( mainly, download contents from the web)? 问题是,每次用户单击该按钮时,我都必须启动一个新线程,或者对于这些小任务(主要是从Web下载内容),线程还有替代方法吗?

You always have to use a different threads. 您始终必须使用其他线程。 Now how you use those different threads can be up to you. 现在,如何使用这些不同的线程将由您决定。 Look at the producer/consumer method where there is just an idle thread sitting in the background waiting for work to be queued. 看一下producer/consumer方法,其中只有一个空闲线程坐在后台等待工作排队。 This seems to fit your job well. 这似乎很适合您的工作。 You should also use SwingWorker when possible because it helps with a lot GUI updates and refreshes. 您还应该尽可能使用SwingWorker ,因为它有助于大量的GUI更新和刷新。 Finally, look at the java.concurrency package as it is very useful. 最后,查看java.concurrency包,因为它非常有用。 Now days, I don't think there is any reason to start a Thread manually without using some library that does all the locking and threading for you. 如今,我认为没有任何理由无需使用一些可以为您完成所有锁定和线程化工作的库来手动启动Thread。

If you want that call to be asynchronous, there's no alternative. 如果您希望该调用是异步的,则别无选择。

However, if you can afford to let your user wait until the download is completed and processed, there's no need for threads. 但是,如果您有足够的时间让用户等待下载完成并处理完毕,则无需线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM