Question

Hi im new in Opp and Java.

I have see something about thread, implements Runnable , start() to call the call the run().

But what does this do?

EventQueue

invokeLater();

Or this full line that you can find in this post on the main method: JTextFields on top of active drawing on JPanel, threading problems

and the Answer on this same on the main method: Java page flipping not supported on Mac OS?

EventQueue.invokeLater(new NewTest());

That call the run() method? what is the difference between that and

Thread var = new Thread(this);
var.start();
Was it helpful?

Solution

The Swing API is single-threaded: you are only allowed to invoke methods on Swing components from the swing thread.

You can have multiple threads in your application, but the moment that another thread needs to interact with the swing components, it needs to do so using EventQueue.invokeLater. This ensures that the Runnable is run on the correct thread.

Starting your own Thread does not have this effect (of running on the Swing thread), so it is not an alternative. If you do it, it may result in data corruption, incorrect screen updates, etc. It may be temporary but it may also be irreparable.

But the invokeLater method is not an alternative to running your own thread or using a thread pool either since all Runnables passed to it are executed in sequence, not in parallel.

OTHER TIPS

I have see something about thread, implements Runnable

Forget that you ever saw that. That was a bad idea that ought to be deprecated. If you want to create an explicit thread in a java program, do it like this:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        ...code to be run in the thread goes here...
    }
});

I'm not going to explain why in this space, but just trust me. It's a good habit to get into now.

what does this do? ...invokeLater...

The swing package creates a thread that responds to "events" (mouse clicks, key presses, etc.), and a lot of the code that you write for swing runs as "handlers" that are called by that thread.

Sometimes, your handler wants to do something that is not allowed/does not make sense in the context in which it is called. I'm not a swing programmer, so I don't have a handy example, but the solution is to call invokeLater()

EventQueue invokeLater(new Runnable() {
    @Override
    public void run() {
        ...code that you want to run "later"...
    }
});

This will post a new event to the event queue, and when the event thread picks it off the queue, it will execute the run() method that you provided.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top