java ExecutorService Callable 任务停止和状态
伊谢尔伦
伊谢尔伦 2017-04-17 13:27:13
0
1
1150

java 并发框架中,使用ExecutorService运行任务,如果是Callable的任务
如何终止耗时比较久的任务(如网络连接),而且Callable任务好像没有Runnable可以查看状态

怎样为每个Callable任务设置超时,超时后停止任务

不像Runnable可以检测到中断信息,还是Callable也可以?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
阿神

// Although it’s been a long time since I asked the question, I still wrote down the answer for everyone’s reference.

Possible ways to set a timeout for the Callable task are as follows:

I. Keep the Futureobject

returned when submitting the task
Future<Object> future = exec.submit(task);

II. Set the timeout period for waiting for the task to return results

int timeout = 5;
future.get(timeout, TimeUnit.SECONDS);

III. Handling timeout exceptions

The complete sample code is as follows:

import java.util.concurrent.*;

public class App {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newSingleThreadExecutor();

        Callable<Object> task = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                for (int i = 0; i < 10; i++) {
                    // 任务需要运行10秒钟
                    TimeUnit.SECONDS.sleep(1);
                }
                return "task result.";
            }
        };

        // 保留提交任务时所返回的`Future`对象
        Future<Object> future = exec.submit(task);

        try {
            // 设置等待任务返回结果的超时时间
            int timeout = 5;
            Object result = future.get(timeout, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            // 处理超时异常
            System.err.println("超时了");
        }

        exec.shutdown();

    }

}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template