Why are two diff. Tasks/Threads ending up on the same thread?
Joined: Feb 25, 2003
I am using a thread pool which takes scheduled tasks. These tasks interact through a socket with the user (via a GUI app). Each task is on a diff. thread in a pool. If one task is already working with the GUI, the second one is supposed to wait (via lockObject.wait() ). However, when I call wait on that object, the GUI becomes unusable. After some checking i discovered it's because somehow those DIFFERENT threads become the SAME thread: "AWT-EventQueue-0". How/why is this? How do I stop them from being run on the same thread so i can do wait/notify?
(I am running these tests/dev on one computer with loopback)
Joined: Feb 25, 2003
I solved the problem but it seems kind of "stupid" (?) and unclean.
Each task had registered itself with a GUIWindow (my class which extends Window) and when a mouse was clicked on the window, an GUIEvent was sent to the task. Since it was sent from within mouseClicked(MouseEvent), apparently Swing uses the same thread as it does for EVERY gui action (e.g. painting), event, etc. So there's no way my task can wait on anything as it causes the same thread (AWT-EventQueue-0) that the other task was running in to also wait (since they're the same thread). To solve it, I simply create a new thread to handle notifying listeners.
This seems like it shouldn't be required, but there's no other way around it. I tried sending the event in SwingUtilities.invokeLater and invokeAndWait and neither one worked.
Joined: Jan 26, 2005
<p> Both invokeLater() and invokeAndWait() cause the Runnable instance to be executed by the Swing event dispatching thread, regardless of which thread calls the method. </p> <p> These methods are used if you want to update a Swing GUI from (e.g.) the Main thread. Quote from the Sun 'How to Use Threads' tutorial: <blockquote> To avoid the possibility of deadlock, you must take extreme care that Swing components and models are created, modified, and queried only from the event-dispatching thread. </blockquote> </p> <p> By the way I'd recommend that Sun tutorial. </p>
author and iconoclast
It's neither stupid nor unclean; it's just how things are supposed to work. It's (supposed to be) well-known that all GUI events are handled on a special event-handler thread, and also that you should never do any long-running processes on the event thread, but rather spawn threads to do them on. Now, you said you are using a Thread pool; your event handlers could, of course, use that pool to run their tasks.