简体   繁体   中英

How to end the processing of other threads when one thread completes in java

I have multiple threads that are performing a search. I'd like it so that when one thread completes the search and finds the solution all the other threads stop running. This is what I have so far

import java.util.Scanner;


class NewThread extends Thread  
{ 

    int n = 4;

    NewThread(String threadname, ThreadGroup tgob, int n) 
    { 
        super(tgob, threadname);
        this.n = n;
        start(); 
    } 
public void run() 
    { 

        System.out.println("Thread running");

                   long timestamp1 = System.currentTimeMillis();

                   System.out.println("Solution to "+ n +" queens using hill climbing search:");

                   HillClimbingSearch hcs = new HillClimbingSearch(n);

                   hcs.runSearch();

                   if (hcs.getFinalSolution() != null)
                   hcs.printState(hcs.getFinalSolution());

                   //Printing the solution          
                   long timestamp2 = System.currentTimeMillis();
                   long timeDiff = timestamp2 - timestamp1;
                   System.out.println("Execution Time: "+timeDiff+" ms");

                   System.out.println(Thread.currentThread().getName() + 
                   " finished executing"); 
    } 
}  

public class Main extends Thread{

    public static void main(String[] args) {


            int n = 0; 
            try (Scanner s=new Scanner(System.in)) {
                while (true){
                    System.out.println("Enter the number of Queens :");
                    n = s.nextInt();
                    if ( n == 2 || n ==3) {
                        System.out.println("No Solution possible for "+ n +" Queens. Please enter another number");
                    }
                    else
                        break;
                }
            }

            // creating the thread group 
            ThreadGroup gfg = new ThreadGroup("parent thread group"); 

            NewThread t1 = new NewThread("one", gfg, n); 
            System.out.println("Starting one"); 
            NewThread t2 = new NewThread("two", gfg, n); 
            System.out.println("Starting two"); 
            NewThread t3 = new NewThread("three", gfg, n); 
            System.out.println("Starting three"); 

            boolean keepRunning = true;

            while(keepRunning){
                if (t1.isAlive() && t2.isAlive() && t3.isAlive()){
                    continue;
                } else {
                    t1.interrupt();
                    t2.interrupt();
                    t3.interrupt();
                    keepRunning = false;
                }
            }

            // checking the number of active thread 
            System.out.println("number of active thread: "
                               + gfg.activeCount()); 

        }
}

This compiles and prints a solution however it prints multiple solutions from each thread that is still running.

My output looks something like this

Enter the number of Queens :
5
Starting one
Thread running
Starting two
Starting three
Thread running
Thread running
Solution to 5 queens using hill climbing search:
Solution to 5 queens using hill climbing search:
Solution to 5 queens using hill climbing search:


0 1 0 0 0 
0 0 0 1 0 
1 0 0 0 0 
0 0 1 0 0 
0 0 0 0 1 
0 1 0 0 0 
0 0 0 1 0 
1 0 0 0 0 
0 0 1 0 0 
0 0 0 0 1 
0 1 0 0 0 
0 0 0 1 0 
1 0 0 0 0 
0 0 1 0 0 
0 0 0 0 1 
Execution Time: 81 ms
Execution Time: 72 ms
Execution Time: 98 ms
one finished executing
two finished executing
three finished executing
number of active thread: 0

Thank you for any help or suggestions.

Here is a suggestion for you.

First, you will need a method that will go through the collection of threads and signal each one to stop. To do this, you'll have to make the thread collection gfg an instance variable, not a variable that is local to the main method.

The method you write for closing the threads should iterate through each NewThread in gfg and set a boolean in it as a signal that it is time to quit.

The NewThread class run() method should periodically look at this boolean. How often is up to you. If the run() finds the that boolean is set, then exit via a branch that goes quietly.

Last thing, when a NewThread completes the task, it should call your method for closing threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM