I'm looking for a clean design/solution for this problem: I have two threads, that may run as long as the user wants to, but eventually stop when the user issues the stop command. However if one of the threads ends abruptly (eg. because of a runtime exception) I want to stop the other thread.
Now both threads execute a Runnable
(so when I say 'stop a thread' what I mean is that I call a stop() method on the Runnable
instance), what I'm thinking is to avoid using threads (Thread class) and use the CompletionService
interface and then submit both Runnables to an instance of this service.
With this I would use the CompletionService's method take()
, when this method returns I would stop both Runnables since I know that at least one of them already finished. Now, this works, but if possible I would like to know of a simpler/better solution for my case.
Also, what is a good solution when we have n
threads and as soon as one of them finishes to stop execution of all the others ?
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…