为线程执行设置timeout
来源:互联网 发布:淘宝店铺怎么申请 编辑:程序博客网 时间:2024/06/05 16:38
- package com.test.threads;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.TimeoutException;
- /**
- * @author Hawkins
- *
- *
- *在指定时间内执行某个task,超时则退出执行。
- */
- public class TimedCall {
- public static void main(String[] args) throws InterruptedException,
- ExecutionException, TimeoutException {
- long timeout = 1000;// 任务必须在设定时间内完成,否则任务将被强制关闭
- long timeNeed = 2000;// 任务完成需要的时长。
- TimeUnit timeUnit = TimeUnit.MILLISECONDS;// 时间单位
- ExecutorService executor = Executors.newSingleThreadExecutor();// 高级并发API
- Runnable task = new MyThread(timeNeed, timeUnit);
- while (!timedCall(executor, task, timeout, timeUnit))
- ;// 在某些场景下,需要不断尝试执行任务,直到能够在限定时间内执行完毕。
- }
- private static boolean timedCall(ExecutorService executor, Runnable c,
- long timeout, TimeUnit timeUnit) throws InterruptedException,
- ExecutionException {
- // FutureTask<?> task = new FutureTask<Object>(c, null);
- // executor.execute(task);
- //
- // task.get(timeout, timeUnit);
- Future<?> future = executor.submit(c);
- try {
- future.get(timeout, timeUnit);
- return true;
- } catch (TimeoutException e) {
- future.cancel(true);// 参数设为true,向执行线程发送中断通知。否则,允许已经启动的线程继续执行直到完成任务。
- System.err.println("任务执行超时,强制退出");
- return false;
- }
- }
- }
- class MyThread implements Runnable {
- long timeLong = 0;// how long thread running will cost
- TimeUnit timeUnit;
- public MyThread() {
- }
- public MyThread(long milli, TimeUnit timeUnit) {
- this.timeLong = milli;
- this.timeUnit = timeUnit;
- }
- @Override
- public void run() {
- System.out.println("---------" + Thread.currentThread().getName()
- + "开始执行,时长[" + timeLong + "]------");
- try {
- Thread.sleep(timeLong);
- } catch (InterruptedException e) {
- System.err.println("线程中断,退出");
- return;// 必须响应中断,否则无法退出线程。在退出之前你可能还需做一些资源回收等等。
- }
- System.out.println("---------" + Thread.currentThread().getName()
- + "执行完毕,时长[" + timeLong + "]------");
- }
- }
0 0
- 为线程执行设置timeout
- 通过线程设置程序timeout
- 为EXt JsonStore设置设置timeOut
- 为Ajax的HTTP Request设置时间限制(Timeout)
- wsimport后如何为jax-ws设置timeout
- 为线程设置名字
- 为线程设置名字
- socket 设置TimeOut
- android Httpclient 设置timeout
- android Httpclient 设置timeout
- session.timeout的设置
- restemplate设置connection timeout
- xfire webservice timeout 设置
- 各种timeout的设置
- SOAPMessage 如何设置timeout
- CloseableHttpClient设置Timeout
- webuploader设置timeout
- CloseableHttpClient设置Timeout
- Android SDK更新以及ADT更新出现问题的解决办法
- 老站长如何运用锚文本来进行站内优化
- C# WinForm中PreviewKeyDown、KeyDown、KeyPress、KeyUp区别与联系
- SEO优化的一些细节问题
- Nutch
- 为线程执行设置timeout
- 你其实没的选择
- 百度算法不断的变化,你会一直坚持吗?
- 正则表达式学习
- Arcgis Engine鹰眼功能的实现
- 【转载】ArcToolbox中的Overlay(叠加分析)功能简介
- 【转载】ArcEngine ITable 与System.DataTable相互转换
- rpm install relocate
- Quartz的cron表达式