当前位置: 代码迷 >> Java相关 >> 各位:线程运行时间过长吗,怎么终止运行
  详细解决方案

各位:线程运行时间过长吗,怎么终止运行

热度:381   发布时间:2016-04-22 21:46:01.0
求助各位:线程运行时间过长吗,如何终止运行?
如下代码:

public class gggg {
public class MRCC implements Callable<Integer>{
public Integer call() throws Exception {
int i = 0;
i = getI();
return i;
}
}
public static int getI(){
while(true){
//模拟一个调用可能需要很长时间才会返回,或者不返回结果的接口(只是模拟,并且这个调用接口不可以更改)
}
}
public static void main(String[] args) {
gggg g = new gggg();
ExecutorService e = Executors.newSingleThreadExecutor();
Future<Integer> f = e.submit(g.new MRCC());
try {
f.get(4000, TimeUnit.MILLISECONDS);
System.out.println("获得了返回值");
} catch (InterruptedException e1) {
System.out.println("中断错误");
} catch (ExecutionException e1) {
System.out.println("执行错误");
} catch (TimeoutException e1) {
f.cancel(true);
System.out.println("超时");
}
                System.out.println(f.isCancelled() + "," + f.isDone());
System.out.println("关闭");
e.shutdown();
}

}


调用一个方法,但是这个方法可能出现长时间无返回值,那么我该怎么结束这个运行超时的线程?
上面代码中用运行过后,线程无法释放,依旧在运行(在eclipse里面测试的时候,打印出“关闭”语句后,程序依然在运行,正常情况下应该是结束的)。
对多线程有点晕头转向了~~又不能强制终结掉Callable类,即使是改用Thread类实现,也无法结束这种类似的线程(我甚至使用了stop()方法),并且Thread方法不能返回值。
预先感谢提供帮助的大大~~求救命~~

------解决方案--------------------
调用该线程的interrupt方法,捕获InterruptedExceprion,保障主线程不因异常退出~
------解决方案--------------------
引用:
引用:

引用:

引用:

小写了个例子:


Java code
package thread.interrupt.call;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import j……



如果是调用别人方法,那就木得好办法了

或许你可以调用别人方法的时候再用一个Future,timeout之后就不管了,反正没法中断,而你的程序却可以继续往下执行
------解决方案--------------------
可能我理解错了,cancel会因为某些原因而无法调用成功。
  相关解决方案