事件驱动线程
我经常遇到这个片段:
{
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new tester(); // class name
}
});
}
我知道我们为什么要使用这个,但无法理解它是如何进行的。我的意思是我不理解这个片段。
(我们正在 run 方法下初始化对象,,,为什么??)
请解释一下
I have often come across this snippet :
{
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new tester(); // class name
}
});
}
I know why are we using this,but cannot understand how it is going.I mean i dont understand this snippet.
(We are initializing object under run method,,,why?? )
Please explain this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用这段代码,您可以创建一个实现 Runnable 的
内部类
,该实例将在 AWT 处理任务调度程序中排队,以便稍后在线程中进行处理。引用文档,invokeLater
...因此,在某个时刻,AWT 调度程序将决定在线程中运行 Runable 的实例。这将引发
run
方法的执行,从而引发new tester();
语句的执行,该语句只是创建tester
类的一个实例代码>.对于你的具体问题...
在 run 方法中创建一个类似乎确实不对,除非构造函数做了很多事情,这实际上是一种不好的做法。
做类似的事情会更直观:
With that bit of code you're creating a
Inner Class
that implementsRunnable
, that instance will be enqueued in the AWT processing task dispatcher for later processing in a thread. Quoting the documentation,invokeLater
...So at some point, the AWT dispatcher will decide to run that instance of Runable in a thread. That will provoke the execution of the method
run
and therefore the execution of the statementnew tester();
, which simply create an instance of the classtester
.To your specific question ...
It really doesn't seem right to just create a class in the
run
method, unless the constructor is doing lots of things which is actually a bad practice.It'be much more intuitive to do something like :
这是在专用线程中注入一些代码的经典方法。 AWT 不是线程安全的(所有 UI 工具包都是线程安全的),因此处理 AWT 的所有代码都必须在特殊线程(事件调度线程 (EDT))中执行。
为此,AWT 有一个要在 EDT 中调用的“代码片段”队列:EventQueue。 EDT 只是一个循环,它将下一个要执行的“代码段”出队并运行它。这些“代码片段”实际上只是
Runnable
实例。这些可以是 UI 事件(鼠标、键盘)或您作为开发人员提供给他的代码。调用
invokeLater
只是告诉 EDT 将Runnable
实例放入其EventQueue
中。您排队的可运行对象将在 EDT 中执行(或更准确地说,将执行其run
方法)。这种将代码从一个线程传递到另一个线程的方法非常常见且有用:它是序列化来自不同线程的代码片段的一种好方法。唯一需要线程安全的是队列本身。
This is a classical way of injecting some code in a dedicated thread. AWT is not thread-safe (as all UI toolkits are), and thus all the code that deals with AWT must be executed in a spêcial thread, the Event Dispatch Thread (EDT).
To do so, AWT has a queue of "piece of code" to be called in the EDT : the EventQueue. The EDT is just a loop that dequeues the next "piece of code" to execute, and runs it. These "pieces of code" are actually just
Runnable
instances. These can be UI events (mouse, keyboard) or code that you, as a developper give to him.Calling
invokeLater
just tells the EDT to enqueue aRunnable
instance in itsEventQueue
. The runnable you enqueued will be executed (or more precisely itsrun
method will be executed) in the EDT, when it will be its turn.This way of passing code from one thread to another is very common and useful : it's a great way of serializing pieces of code that come from different threads. The only thing that needs to be thread-safe is the queue itself.