Event Driven Thread

2019-07-27 21:56发布

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

2条回答
贪生不怕死
2楼-- · 2019-07-27 22:19

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 ...

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

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??

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 :

SwingUtilities.invokeLater(new Runnable()
   {
   public void run() {
     Tester t = new Tester();
     t.doSomeStuff();
   }
 });
查看更多
Luminary・发光体
3楼-- · 2019-07-27 22:34

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 a Runnable instance in its EventQueue. The runnable you enqueued will be executed (or more precisely its run 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.

查看更多
登录 后发表回答