This content has been marked as final. Show 2 replies
The usual way to tell a thread to stop doing what it is doing is via a boolean flag in the thread.1 person found this helpful
Initialize it to false. Then the thread will periodically check it and terminate if it has been set to true. Obviously, then, if you want the thread to terminate then you set the flag to true.
This implies you have to write your threads so that they do check the flag regularly while they're doing their work.
Also note that once you get a reply from one node, by the time you notify all of the other threads to knock it off, some of them may already have got replies from their nodes. If you want those other threads to not act upon the reply, then you need a shared object which only allows one thread to proceed. A CountdownLatch would be a good tool for this, I think.
It's also possible (and quite likely) that you could write a customized ExecutorService which took care of all those details for you. I haven't had all that much experience with Executors so I can't envision all of the details, but that's what I would try if I could. My point of view is that low-level threading with wait() and lock() still exists, but you should really try to do things in java.util.concurrent as much as possible for real-life programming.
crottyan wrote:You want to use an ExecutorCompletion service. in fact, the class javadoc for ExecutorCompletionService has exactly this example (second example).
1) I'd like to spawn a new thread to wait for a reply from each individual node concurrently. What is the best way to achieve this?
2) As soon as one node replies (firstReplier), I'd like the parent to continue processing with that node, and also to instruct all other threads waiting for replies from other nodes to terminate. What is the best way to achieve this?
Edited by: jtahlborn on Sep 19, 2012 10:04 PM