IamBATMAN
IamBATMAN

Reputation: 39

How to stop a thread if one thread has completed a task first?

You have to find a file from your two drives of computer. If one thread found it first then the second thread will stop.

Upvotes: 3

Views: 1561

Answers (3)

morpheus05
morpheus05

Reputation: 4872

The first thing is, you cannot force a thread to stop in java. To stop a thrad safely it has to terminate "naturally". (Means, all the code inside has to be executed or an exception occurs which is not caugth).

In Java you can use the "interrupt" flag. Have both you threads check Thread.currentThread().isInterrupted() like this:

try {
    while(!Thread.currentThread().isInterrupted()) {
       [...]
       Thread.sleep(); //May be you need to sleep here for a short period to not produce to much load on your system, ?
    }
 } catch (InterruptedException consumed) {
 }

So the easiet implementation would be to have your two threads have a reference to one another and if one thread found the file it calls interrupt on the other thread which in turn terminates because of the above while loop.

For more information look Java Concurrency in practice.

Upvotes: 1

Ehler
Ehler

Reputation: 325

You can try to use a flag whether the file was found. The thread will exit if the flag changes its state.

Example with an implemented Runnable

public class Finder implements Runnable {

    private static boolean found = false;

    @Override
    public void run() {
        for (ITERATE_THROUG_FILES) {
            if (found) {
                break;
            }

            if (FILE == SEARCHED_FILE) {
                found = true;
            }
        }
    }
}

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881323

Have all threads periodically check a flag variable to see if it's been set and then stop searching if it has. You could do this check after each file, after each directory, or if it's been more than a second since the last time you checked, the mechanics are up to you, depending on your needs.

Then just have a thread set that flag if it finds the file. The other threads will soon pick it up and stop as well.

I prefer having each thread responsible for its own resource, including its lifespan, that's why I prefer this sort of solution to trying to kill a thread from outside it.

I don't know whether Java suffers from the same issues as pthreads (in terms of destroying threads that hold critical resources) but I'd rather be safe than sorry.

Upvotes: 1

Related Questions