我正在做一些关于线程的练习。 我的问题是如何在函数完成时终止一个包装函数的Thread(并将大部分时间用于活动),并在java中返回结果。
这是一个函数示例:
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;
}
这是我的代码,我不确定它是否有效:
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;
}
}
答案 0 :(得分:0)
单向处理InterruptedException,使用Thread.interrupt(),
更多内容如下: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
更多关于在没有Thread.stop()的情况下停止线程:
https://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html