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.
this is an Example of a function:
public static boolean isPrime(long n){
    boolean ans=true; 
    if(n<2)throw new RuntimeException("ERR: the parameter to the isPrime function must be >1 (got "+n+")!");
    int i=2;  double ns=Math.sqrt(n) ;  
    while(i<=ns&&ans){ 
        if (n%i==0) ans=false; 
        i=i+1;  
    }  
    if(Math.random()<Ex4_tester.ENDLESS_LOOP)while(true); 
    return ans;  
}
this is my code and I'm not sure if it works:
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()) && (check.finish)) {
            check.stop();           
        }
        return check.ans;
    }
}
 
     
    