posted 16 years ago
Susan,
A couple of things come to mind here. I think you need you clarify a little bit about what it is you're trying to do. In the run method, you said you want to return some values to the main method. Remember that the run method can't actually return any values. As for stopping all threads once a result is found, you can only stop a thread if it has a flag that it is periodically checking (since Thread.stop is inherently unsafe and deprecated).
When you're starting a bunch of threads like you are doing in your example, it is typically a good idea to use a thread Executor service. This allows an available pool of threads to complete the tasks you want to run rather than starting a new thread for each one (saves on the cost of starting new threads -- all threads aren't going to be running at once, so you might as well save resources). Another major benefit to using an executor service is that you can in fact cancel any tasks that haven't started yet. And you can also submit Callable tasks which can return a value.
The basic algorithm for your problem might be something like:
create an executor service
continue to read each line from the csv file as you do now, but instead of starting a new thread, submit a Callable that is similar to your run method but returns field1 and field2 and you could have another thread that is checking which callables are complete and evaluating the results. you could also use a Runnable here and the runnable itself could check if field1 != 0 and field2 != 0 and notify listeners (or invoke another method or something else) when these conditions hold true. this second method of using a runnable might actually be preferable so you don't need to have a thread that is polling the callables to see if they are finished. depending on your requirements you could choose between a polling vs notification system.
once a result is found, cancel all tasks that are currently queued in the executor. any currently executing tasks will finish but you could ignore their results (or if it's really important to stop immediately and exit the application, they could always be daemon threads, but it seems like the processing is not very intensive, so finishing remaining tasks should be negligible).
Hope this helps,
Jeff