事件驱动线程 [英] Event Driven Thread

查看:42
本文介绍了事件驱动线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到这个片段:

{

 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.

(我们在run方法下初始化对象,,,为什么??)

(We are initializing object under run method,,,why?? )

请解释一下

推荐答案

使用这段代码,您将创建一个实现 RunnableInner Class,该实例将在 AWT 处理任务调度程序中排队,以便稍后在线程中处理.引用文档,invokeLater ...

With that bit of code you're creating a Inner Class that implements Runnable, that instance will be enqueued in the AWT processing task dispatcher for later processing in a thread. Quoting the documentation, invokeLater ...

导致执行 doRun.run()在 AWT 事件上异步调度线程.这会发生在所有待处理的 AWT 事件都被处理后已处理.

Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed.

因此,在某些时候,AWT 调度程序将决定在线程中运行 Runable 的该实例.这将引发方法 run 的执行,从而引发语句 new tester(); 的执行,它只是创建 tester.

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 statement new tester();, which simply create an instance of the class tester.

对于您的具体问题...

To your specific question ...

我们正在初始化运行中的对象方法,,,为什么?

We are initializing object under run method,,,why??

只在 run 方法中创建一个类似乎确实不正确,除非构造函数做了很多事情,这实际上是一种不好的做法.

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.

这样做会更直观:

SwingUtilities.invokeLater(new Runnable()
   {
   public void run() {
     Tester t = new Tester();
     t.doSomeStuff();
   }
 });

这篇关于事件驱动线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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