java超时关闭线程,用future.get() 实现

这个我研究了两天,好多都是用的future.get(超时时间,单位)来实现,只是不同方式而已。下边来看下:

第一种:

//先新建一个 ExecutorService 
ExecutorService exec = Executors.newSingleThreadExecutor();
//新建future,callable,call  //返回值为String,任何类型都可以
FutureTask<String> future = new FutureTask<String>(
                new Callable<String>() {
                    public String call() {
                       //需要定时检测的方法,写在此处
                        return "";  
                    }
                });
//加载future
exec.execute(future);

try {
//future的get()设定超时时间
String result = future.get(3900, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    future.cancel(true);   //关闭future(关闭异常的监测方法)
 // 做出对应异常的反应
} catch (ExecutionException e) {  
 future.cancel(true);   //关闭future(关闭异常的监测方法 ,此异常标识方法内部异常)
 // 做出对应异常的反应            
} catch (TimeoutException e) {
    future.cancel(true);   //关闭超时线程
  // 做出对应异常的反应    
} finally {
    exec.shutdown(); 
} 

第二种:

//若线程超时关闭
ExecutorService exec = Executors.newFixedThreadPool(1); 
//call(), 真正检测的方法体在此。
Callable<InterfaceUpdateDto> call = new Callable<InterfaceUpdateDto>() {
    public InterfaceUpdateDto call() {
    	return ins.updateAndSelectByNodeId(dataj, nodeId);
    }
};

Future<InterfaceUpdateDto> future = exec.submit(call);	
try {
	//future的get()设定超时时间
	InterfaceUpdateDto interfaceUpdateDtoData = future.get(3900, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    future.cancel(true);
    snmpList = ins.selectByNodeId(nodeId);
    canCollect = "noCollect";
} catch (ExecutionException e) {  
//因为在call()方法体内无法完成数据更新需要的数据库查询,遂再次再次更新操作
    future.cancel(true);
    InterfaceUpdateDto interfaceUpdateDto =  ins.updateAndSelectByNodeId(dataj, nodeId);
    snmpList = interfaceUpdateDto.getSnmpList();
    canCollect = interfaceUpdateDto.getCanCollect();
} catch (TimeoutException e) {
    future.cancel(true);
    snmpList = ins.selectByNodeId(nodeId);
    canCollect = "noCollect";
} finally {
    exec.shutdown();
}	

这几种都能实现,但是我需要定时检测的方法一在try中执行(一旦访问数据库)就会进入 异常,我debug调试了好久都没有找到原因,就暂时的找了一个解决办法 ——> 既然能正常检测超时,那我现在只要保证在不超时的情况下,正常进行我的方法就行了,我发现每次都会就入 异常,方法没执行完(跟新端口信息),于是我就将方法放到这个异常的catch{} 中,总之是完成了任务。

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值