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