为什么Swing线程模型被认为是错误的,应该如何? [英] Why is Swing threading model considered wrong and how should it be?

查看:134
本文介绍了为什么Swing线程模型被认为是错误的,应该如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次听说Java Swing线程模型是错误的。我不完全理解为什么,我知道这个问题与你可以从主UI线程以外的另一个线程中绘制 Drawable 的事实有关。我知道有一些实用功能,比如 SwingUtilities.invokeAndWait SwingUtilities.invokeLater 可以让你在 Runnable ,它又由Event Dispatcher线程运行。我猜这种方式可以确保绘画是同步完成的,这不会使缓冲区处于不稳定的状态。

I heard many times that Java Swing threading model is wrong. I don't fully understand why, I know that the problem is related to the fact that you can draw on a Drawable from another thread other than the main UI thread. I know that there are utility functionalities like SwingUtilities.invokeAndWait and SwingUtilities.invokeLater that let you do your painting in a Runnable, that in turn is run by the Event Dispatcher thread. I guess that this way you ensure that painting is done synchronously and this doesn't leave the buffer in an incosistent state.

我的问题是:好的UI工具包的行为如何?采用了哪些解决方案?

My question is: how do "good" UI toolkits behave? What solutions are adopted?

推荐答案

Brian Goetz的 Java实践中的并发性

Brian Goetz's Java Concurrency in Practice,

9.1为什么GUI是单线程的?


...在过去,GUI应用程序是单线程的,GUI事件
是从主事件循环处理的。现代GUI框架使用的
模型略有不同:它们创建一个专用事件
调度线程(EDT)来处理GUI事件。单线程GUI
框架并不是Java独有的; Qt,NextStep,MacOS Cocoa,X
Windows以及许多其他人也是单线程的。这不是
缺乏尝试;已经有很多尝试编写多线程的
GUI框架,但由于种族
条件和死锁的持续问题,他们最终都到达了
单线程事件队列模型,其中有一个专用线程从队列中获取
事件并将它们分派给应用程序定义的事件
处理程序...

...In the old days, GUI applications were single-threaded and GUI events were processed from a "main event loop". Modern GUI frameworks use a model that is only slightly different: they create a dedicated event dispatch thread (EDT) for handling GUI events. Single-threaded GUI frameworks are not unique to Java; Qt, NextStep, MacOS Cocoa, X Windows, and many others are also single-threaded. This is not for lack of trying; there have been many attempts to write multithreaded GUI frameworks, but because of persistent problems with race conditions and deadlock, they all eventually arrived at the single-threaded event queue model in which a dedicated thread fetches events off a queue and dispatches them to application-defined event handlers...

这篇关于为什么Swing线程模型被认为是错误的,应该如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆