简体   繁体   English

GUI应用程序的多线程

[英]Multithreading on GUI applications

I am developing a Java application and I am at the phase of writing the GUI code. 我正在开发一个Java应用程序,我正处于编写GUI代码的阶段。 For some reason I am getting crashes on the app with crash reports (not just errors on netbeans console). 出于某种原因,我在应用程序上遇到崩溃报告(而不仅仅是netbeans控制台上的错误)。 I wonder if there are problems with the way I am handling events as the report often says AWT dispatch thread crashed. 我想知道我处理事件的方式是否有问题,因为报告经常说AWT派遣线程崩溃了。

Should I be creating a new thread to handle the different events firing from GUI ? 我应该创建一个新线程来处理从GUI触发的不同事件吗?

For example by making use of : 例如,通过使用:

Executors.newCachedThreadPool().execute(new Runnable() {
                    public void run() {}});

Is it possible that something like that fix the crashes? 有可能像这样的东西修复崩溃吗? Would it have negative impact on application performance ? 它会对应用程序性能产生负面影响吗?

You are probably accessing Swing from multiple threads. 您可能正在从多个线程访问Swing。 Neither AWT nor Swing are thread safe. AWT和Swing都不是线程安全的。 Consider using the SwingWorker class in order to ensure that it is not accessed outside of the Event Dispatch Thread. 请考虑使用SwingWorker ,以确保不会在Event Dispatch Thread之外访问它。

For more information, here's another answer I have given about SwingWorker . 有关更多信息,这是我给出的关于SwingWorker另一个答案

Make sure all your method calls that update the GUI from different threads than the GUI thread are forwarded to the GUI thread using SwingUtilities.invokeLater . 确保使用SwingUtilities.invokeLater从GUI线程转发到GUI线程的所有方法调用都从不同的线程更新GUI。 Other threads should never change the GUI directly. 其他线程永远不应该直接更改GUI。

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

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