How can I stop a thread if one thread completed the task in the first place?

You need to find a file from two disks of your computer. If one thread finds it first, then the second thread will stop.

+3


source to share


3 answers


Check the flag variable periodically to make sure it is set and then stop searching if there is one. You can run this check after every file, after every directory, or if more than a second has passed since the last check, the mechanics depend on your needs.

Then just set thread this flag if it finds the file. Other threads will soon pick it up and stop it as well.



I prefer that each thread is responsible for its own resource, including its lifetime, so I prefer this solution for trying to destroy the thread from the outside.

I don't know if Java is experiencing the same problems as pthreads (in terms of killing threads that contain critical resources), but I'd rather be safe than sorry.

+1


source


First, you cannot force the thread to stop in java. To stop a trade safely, it must end "naturally". (Means that all the code inside must be executed or an exception is thrown, which is optional).

In Java, you can use the "interrupt" flag. Ask both of these threads to check Thread.currentThread (). IsInterrupted () as follows:

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 for your two threads to have a link to each other, and if one thread finds the file, it triggers an interrupt on the other thread, which in turn exits due to the above loop.

See Java Concurrency in Practice for more information.

+1


source


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

Example with 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;
            }
        }
    }
}

      

0


source







All Articles