user3970513
user3970513

Reputation: 11

Exiting a thread in java

Thread som;    
static  class solver implements Runnable  {                                 
       public void distancecalculator(char [][]problem , Point start , 
       int distancefound) {
       // Some code and condition to exit from program if satisfy 
       solver s = new solver(newproblem , neworigin,dist[a][b] );
       som =  new Thread(s);
       som.start();
    }

    public void run(){                  
       //som.sleep(1000);
       //System.out.println("check");
       distancecalculator(prom,movepoint ,disadd ); //Making a recursive call                       
    }

I am generating threads on every recursive call, I want that in control way i.e. if 500 threads are generated then terminate the first 100 threads. How can i achieve this? If i use som.sleep which thread will sleep the newly generated one or old one?

Upvotes: 0

Views: 119

Answers (2)

Braj
Braj

Reputation: 46841

Just use ExecutorService and create poll of n threads using Executors.newFixedThreadPool(int) factory method.

Find the example code in the above link and here as well.

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200158

  1. sleep is a static method. It makes the calling thread sleep. More generally, there is no direct way to make another thread do anything, including sleep. You need a specific inter-thread communication mechanism for any such task.

  2. Make a thread end by following the rules of the interruption mechanism (consult the documentation for Thread#interrupt() and Thread#isInterrupted().

Upvotes: 2

Related Questions