Nikki
Nikki

Reputation: 3674

Dispatch a task from EDT to main?

I've been reading a bit about concurrency (which gives me a headache).

I understand you can set a task to run on the EDT from the main thread using:

SwingUtilities.invokeLater

but can you set a task to run on the main thread from the EDT?

As in:

Thread mymainthread=Thread.currentThread();//<referring to the thread that initially kicks off public static void main

public void mousePressed(MouseEvent e){ //queue a task to run on mymainthread }

Can it be done? Is it a bad idea?

The other question on SO similiar to this (here) talks about creating a new thread but wouldn't it be safer and simpler to keep using the main if I was aiming for a single thread (+EDT) application? .......or maybe I've got this all wrong.

EDIT: What I should have explained: I wanted to create objects that would communicate with each other on the main thread (running in a slow loop) so I didn't want any of them be instantiated on a different thread, edt or otherwise.

Upvotes: 2

Views: 274

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147144

You can create your own event loop to do thread-confinement. This would allow you a separate single thread which would behave like the EDT. Be careful not to share [effectively] mutable objects between the two threads simultaneously.

Implementation can be as simple as a while loop with a BlockingQueue. You can go slightly higher level by getting an ExecutorService from java.util.concurrent.Executors.newFixeThreadPool(1).

Upvotes: 2

Cratylus
Cratylus

Reputation: 54074

but can you set a task to run on the main thread from the EDT?

I think you are confused on what EDT is. Swing and many other frameworks use a technique called thread-confinement.
In order to guarantee thread-safety, all actions are executed from a single thread. This thread in Swing is called Event Dispatcher Thread.
This thread has a queue and executes all tasks from that queue sequentially one at a time, at the same thread. This is why your tasks should be short in order not to block the UI.
So when you use EDT you are essentially passing a task to its queue from your thread and EDT will eventually execute it.
What you can do is put a task on the EDT queue which spawns a thread to be executed on separate thread. If you want to use your current thread for some reason as the background thread perhaps you could but why would you need that? The most straightforward way is just to submit a runnable to run as part of some background thread e.g. part of a pool

Upvotes: 5

Related Questions