For test things, I want to launch a process on the swing edt, and wait for a result.
Usualy, I do that with a invokeAndW开发者_开发知识库ait. But perhaps is it possible to use a FutureTask, and launch this task on the EDT ??
Is it possible, and have you an exemple of (my) idea ?
Thanks.
EventQueue.invokeAndWait
behaves much the same as a lock. A lock with an awful lot inside, which is against the usual advice to keep short. It therefore is prone to cause deadlocks, and I'd recommend avoiding it.
Run a task on the EDT with EventQueue.invokeLater
. Have that task run a task on your thread using a task queue. (Only avoid statics, and I suggest using a non-static wrapper around invokeLater
so that you can test and monitor).
It's good that you know that Swing component manipulation must be done in the event dispatch thread, but the simple answer is no, you never want to start a long-running task or wait on locks while in the EDT. The EDT should always remain highly responsive. Also, as an aside, invokeAndWait()
cannot be called from the EDT, for obvious reasons.
Take a look at this old article about Threads and Swing - the basic principles still apply.
You have several options open to you. You can simply create a new Thread
, Runnable
or FutureTask
to run on an Executor
, and call invokeAndWait()
only when necessary to update components (but if you can get away with it, invokeLater()
is better). You could also use a SwingWorker
(also in the article), which provides additional useful ways of interfacing between your thread and the EDT with a proper degree of separation.
精彩评论