简体   繁体   English

Java Threading-Swing应用

[英]Java Threading - Swing app

I'm trying to learn how to thread a class (specifically a method in a class) and I've come across Thread() and SwingWorker() . 我正在尝试学习如何对类(特别是类中的方法)进行Thread()并且遇到了Thread()SwingWorker() This is a swing application. 这是一个摇摆应用程序。 Which should I choose and why? 我应该选择哪个?为什么选择? Also, is there some generic way to add implementation for threading to existing methods? 另外,是否有一些通用的方法可以将实现添加到现有方法中?

Thanks 谢谢

SwingWorker is mainly for executing background processes in Java Swing means UI based application , like on pressing a Button in a UI , you want some long process to happen in Background. SwingWorker主要用于在Java中执行后台进程Swing意味着基于UI的应用程序,就像在UI中按下Button一样,您希望在Background中进行一些长时间的处理。 Thread is normally used to multitasking in Java Programs like executing two operations in a time kind of stuffs. 线程通常用于Java程序中的多任务处理,例如在某种时间里执行两个操作。 Thread can be implemented from Runnable interface as well as inherited from thread Class. 线程可以从Runnable接口实现,也可以从线程Class继承。 Check Oracle Java Docs. 检查Oracle Java文档。

Using Swingworkers would probably make your like easier because it is meant to do exactly what you need. 使用Swingworkers可能会使您更轻松,因为它可以完全满足您的需求。 There is a good tutorial on Oracle's website that would get you started. 在Oracle网站上有一个很好的教程可以帮助您入门。 In essence, in a Swing application, you need to make sure that: 本质上,在Swing应用程序中,您需要确保:

  • Anything that interacts with the GUI runs in the EDT (Event Dispatch Thread) 任何与GUI交互的内容都在EDT(事件调度线程)中运行
  • Long tasks do not run on the EDT because if they do they will freeze the GUI while your computation is running 长任务无法在EDT上运行,因为如果执行了长任务,则它们将在计算运行时冻结GUI

Swingworkers handle those 2 things very well. 摇摆工作人员很好地处理了这两件事。

Class Thread is a basic piece you need to create threads. Thread是创建线程所需的基本部分。 JDK provides either "low level" API (take a look on class Thread, interface Runnable, synchoronized keyword, methods wait() , notify() ) or higher level API (SwingWorker, Timer, executors framework). JDK提供了“低级” API(请查看类Thread,接口Runnable,synchoronized关键字,方法wait()notify() )或更高级别的API(SwingWorker,Timer,执行程序框架)。

There is a lot of tutorials in web. 网络上有很多教程。 Learn basics first. 首先学习基础知识。 Read javadoc of Thread, find some examples, play with them. 阅读Thread的javadoc,找到一些示例,然后进行操作。 Then go through Timer and SwingWorker. 然后通过Timer和SwingWorker。 It will be simple. 这很简单。 Then, when you understand how is it working take your time to study executors, thread pools etc. 然后,当您了解它是如何工作的时,便需要花时间研究执行程序,线程池等。

Happy threading! 线程愉快!

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

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