Have a Thread wait for a Condition
In a GUI, I have a few buttons. These buttons spin off worker threads that send requests over the network to a server. In a seperate thread, there is a listener that receives the responses from the server. This response is passed to the same object that the worker threads are executing methods on via the Observer/Observable interface.
What I need to do is to have the worker threads wait for a response from the server that pertains to them. Essentially a worker thr开发者_运维百科ead should send the command, then wait for some condition that indicates the right response was received. I can think of multiple ways to do this (sleeping, polling, wait, notify, monitors, etc), but is there a particular method that would be best in this situation?
I would recommend to use a high level "locking" mechanism from the java.util.concurrent package Eg a CountDownLatch -- "A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. "
This doesn't seem like a place you want to block at all. You are already in a worker thread so you aren't holding any kind of state for your GUI or anything, I'd send the message and bail--when your response comes back, grab another thread out of the pool and send it on it's merry way.
If you have data that is shared between the two, put it into its own object in a collection keyed by some common value and have the new thread pull it out when it comes in.
For readability/simplicity make the object with the data also contain the code that knows how to handle that data so that all you have to do when you get an incoming message is retrieve a key that uniquely identifies which object sent it, retrieve that object by the key and call that object's "Data received" method passing in the information you got from the packet.
The nice thing about this is it makes it trivial for a simple listener to handle a huge variety of incoming packets by making the "Data received" method an interface that many different handlers can implement.
OO is cool, eh?
精彩评论