java多线程实现任务超时监听 - huangying2124的专栏 - 博客频道 - CSDN.NET
使用Future的特性(推荐)
利用Future.get(long timeout, TimeUnit unit)方法。
1、新建TaskThread类,实现Callable接口,实现call()方法。
2、线程池调用submit()方法,得到Future对象。
3、调用Future对象的get(long timeout, TimeUnit unit)方法,该方法的特点:阻塞式线程调用,同时指定了超时时间timeout,get方法执行超时会抛出timeout异常,该异常需要捕获。
示例代码:
- public class TimeTask implements Callable<String> {
- @Override
- public String call() throws Exception {
- //执行任务主体,简单示例
- Thread.sleep(1000);
- return "hehe";
- }
- }
- ExecutorService exec = Executors.newCachedThreadPool();
- Future<String> f = exec.submit(new TimeTask());
- try {
- f.get(200, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- } catch (TimeoutException e) {
- //定义超时后的状态修改
- System.out.println("thread time out");
- e.printStackTrace();
- }
Google Guava已经提供了TimeLimiter的功能,实现更精巧,功能更强大,可参考:
- import com.google.common.util.concurrent.SimpleTimeLimiter;
- public class TimeLimiterGoogle {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- SimpleTimeLimiter st = new SimpleTimeLimiter();
- String r1 = st.callWithTimeout(new Callable<String>(){
- @Override
- public String call() throws Exception {
- return "Hello";
- }}, 10, TimeUnit.MILLISECONDS, true);
- System.out.println(r1);
- String r2 = st.callWithTimeout(new Callable<String>(){
- @Override
- public String call() throws Exception {
- Thread.sleep(1000);
- return "Hello";
- }}, 10, TimeUnit.MILLISECONDS, true);
- System.out.println(r2);
- }
- }