项目最近写了一个接口,设定不断的去请求第三方获得数据,由于网络等等原因,httpClient请求偶尔会超时,超时后进入假死状态,卡死。查询了一下好像是httpClient 3.x存在这种问题,在4.x后已经修复。
如果想一个别的路子:譬如,捕捉每一次httpClient请求,判断该线程的执行时间,如果超过常规值则将该线程杀掉,下面的工作则可以正常进行了。
搜罗一下有两种可行的方案。
一、CounterThread.join()方法
import java.util.concurrent.*;
/**
* Created by liyang on 2017/9/4.
*/
public class ThreadTest {
public static void main(String[] args) {
CounterThread ct = new CounterThread(1314);
ct.start();
try {
ct.join(5000); //超时的时间,如5秒
if(ct.isAlive()){//说明再设定的时间内没有执行完,超时
ct.interrupt();
throw new TimeoutException();//抛出,让socket线程终止
}
//正常情况下可以获取执行后的值
System.out.println(ct.getResult());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
System.out.println("then,we take zhe next step!");
}
}
class CounterThread extends Thread {
// 构造函数,传递一些有用的值给run;
public CounterThread(int time) {
this.result = time;
}
private int result;
public int getResult() {//在上面获取的结果值
return result;
}
public void run() {
// 执行的任务,如读取客户端数据
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
二、ExecutorService.submit(Thread).get()
此方法经验证是我最喜欢的方法。
package com.ane56.Demo20170904;
import java.util.concurrent.*;
/**
* Created by liyang on 2017/9/4.
*/
public class TimeoutTest1 {
public static void main(String[] args) {
final ExecutorService service = Executors.newFixedThreadPool(1);
TaskThread taskThread = new TaskThread();
System.out.println("提交任务...begin");
Future<Object> taskFuture = service.submit(taskThread);
System.out.println("提交任务...end");
try {
Object re = taskFuture.get(6000, TimeUnit.MILLISECONDS);//超时设置,6s
System.out.println(re);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("超时 取消任务");
taskFuture.cancel(true);
System.out.println("超时 取消任务OK");
} finally {
service.shutdown();
}
System.out.println("then,we take zhe next step!");
}
}
class TaskThread implements Callable<Object> {
public Object call() throws Exception {
String result = "空结果";
try {
System.out.println("任务开始....");
Thread.sleep(5000);
result = "正确结果";
System.out.println("任务结束....");
} catch (Exception e) {
System.out.println("Task is interrupted!");
}
return result;
}
}