title: How to terminate a Thread that wraps a function?
body: <p>I'm doing a cours Exersice about Threads.
  my question is how to terminate a Thread that wrap a function (and recives maximu time to be alive) when the function finished and return the result in java.</p>
  
  <p>this is an Example of a function:</p>
  
  <pre><code>public static boolean isPrime(long n){
      boolean ans=true; 
      if(n&lt;2)throw new RuntimeException("ERR: the parameter to the isPrime function must be &gt;1 (got "+n+")!");
      int i=2;  double ns=Math.sqrt(n) ;  
      while(i&lt;=ns&amp;&amp;ans){ 
          if (n%i==0) ans=false; 
          i=i+1;  
      }  
      if(Math.random()&lt;Ex4_tester.ENDLESS_LOOP)while(true); 
      return ans;  
  }
  </code></pre>
  
  <p>this is my code and I'm not sure if it works:</p>
  
  <pre><code>public class Ex4 {
  
      private class myThread extends Thread {
          private long n;
          private boolean ans;
          private boolean finish = false;
          public myThread(Long n) {
              this.n = n;
          }
  
          @Override
          public void run() {
              ans = Ex4_tester.isPrime(n);
              finish = true;
              System.out.println(ans);
  
          }
      }
  
      @SuppressWarnings("deprecation")
      public boolean isPrime(long n, double maxTime)  throws RuntimeException, InterruptedException {
          myThread check = new myThread(n);
          check.start();
  
          try {
              check.join((long)(maxTime * 1000));     
          }
          catch (InterruptedException e) {
              e.printStackTrace();
          }
  
          if ((check.isAlive()) &amp;&amp; (check.finish)) {
              check.stop();           
          }
          return check.ans;
      }
  }
  </code></pre>