怎么给一个函数的运行设置超时
来源:互联网 发布:c语言病毒源码 编辑:程序博客网 时间:2024/05/29 19:55
首先,为了使系统资源能更好分配,建立一个线程池:
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(3); //Integer.MAX_VALUEExecutorService mExecutor = new ThreadPoolExecutor(4, 6, 4, TimeUnit.SECONDS, workQueue, new ThreadPoolExecutor.CallerRunsPolicy());
接着实现接口Callable的抽象方法call:
Callable<Integer> callable = new Callable<Integer>() { public Integer call() throws Exception { int result = reader.read(); return result; } };
注意此call方法中的代码就是要对其实现超时机制的方法
然后把此callable对象作为构造参数,如下,产生一个FutureTask对象,因为FutureTask是Runnable的子类,所以可以把它提交给线程池来运行:
final FutureTask<Integer> future = new FutureTask<Integer>(callable); mExecutor.submit(future);//启动线程执行耗时操作 TimeOutRunnable timeOutRunnable = new TimeOutRunnable(0x3551,handler,1000 * 30,future); mExecutor.submit(timeOutRunnable);//另启动一个线程来接收其返回值
与此同时,必须启动一个计时线程。后面两行就是启动一个计时线程来接收future对象的返回值,也就是耗时操作的返回值。计时线程具体实现如下:
package com.sodo.thread;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import com.sodo.util.LogUtils;import android.os.Handler;public class TimeOutRunnable implements Runnable {private String TAG = "TimeOutRunnable";private int msg;Handler handler;long outtime = 0L;Integer obj = -1;FutureTask<Integer> future = null;public TimeOutRunnable(int msg,Handler handler,long outtime,FutureTask<Integer> future) {this.msg = msg;this.handler = handler;this.outtime = outtime;this.future = future;}@Overridepublic void run() {// TODO Auto-generated method stubtry {if(future != null) {obj = future.get(outtime, TimeUnit.MILLISECONDS);}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();obj = 2;} finally {if(handler != null) {handler.obtainMessage(msg, obj).sendToTarget();} else {LogUtils.e(TAG, "handler null");}}}}
future.get(outtime,TimeUnit.MILLISECONDS)是一个阻塞方法,阻塞的时间是30秒,如果超过30秒future还没有返回,那么就会抛出TimeoutException。所以,UI就会根据此线程返回的obj值来显示相应的信息,如果obj等于2的话,代表的就是超时。
0 0
- 怎么给一个函数的运行设置超时
- java,如何给一个任务设置超时限制
- 给XMLHttpRequest设置超时时间
- 给XMLHttpRequest设置超时时间
- 给XMLHttpRequest设置超时时间
- 给XMLHttpRequest设置超时时间
- 给xmlhttprequest设置超时限制
- 怎么给一个运行中的程序模拟按键啊?
- 一个调用函数引发的超时!
- connect函数超时设置
- 设置函数超时
- 怎么实现带超时功能的 connect 函数
- QT怎么给一个文件设置读写权限
- 怎么给视图的字段一个默认值
- 如何设置ASP.NET页面的运行超时时间
- 如何设置ASP.NET页面的运行超时时间
- 给进程指定一个新的运行程序的函数exec()
- 一个exe文件怎么运行起来的
- 在 MyEclipse/Eclipse 中如何查看某个文件的历史记录
- iOS 在google地图上显示自己的位置
- Avoid passing null as the view root
- nginx和 apache比较
- 黑马程序员——ios开发基础之OC简介
- 怎么给一个函数的运行设置超时
- tp pc,m 在共用一个框架的情况下,共用模型
- (2.1.2.6)java自带线程池和队列详细讲解
- makefile---单多个源文件,单个可执行文件(C/C++)
- win7 64打开文件夹总是新窗口打开的解决办法
- 【翻译+山寨】html5+css3+js实现翻页翻书效果
- 马良建模学习笔记——软包制作四
- AMBA、AHB、APB、ASB总线简介
- ubuntu 按键remap