小编use*_*186的帖子

Java - 在ExecutorCompletionService中定义Callable的超时

我使用ExecutorCompletionService遇到了以下问题.我想在不同的线程中调用很多Callable.这些Callable不会彼此共享任何信息.我需要为每个Callable定义一个超时,例如.运行时间不要超过5秒.每个Callable都可以在启动时不知道的不同时间运行.在超时之后,线程应该被停止/杀死,结果对我来说不再有趣.不应该影响其他"正常"运行的线程.

因此,让我们以简单的可调用和我当前的Java代码为例.

import java.util.Date;
import java.util.concurrent.Callable;

public class Job implements Callable<Integer> {

    int returnValue = 0;
    long millis = 0;

    public Job(long millis, int value) {
        this.millis = millis;
        this.returnValue = value;
    }

    @Override
    public Integer call() throws Exception, InterruptedException {
        try {
            System.out.println(new Date() + " " + returnValue + " started");
            Thread.sleep(millis);
            System.out.println(new Date() + " " + returnValue + " finished");
            return returnValue;
        } catch (InterruptedException e) {
            System.out.println(new Date() + " " + returnValue …
Run Code Online (Sandbox Code Playgroud)

java multithreading timeout callable executorservice

7
推荐指数
2
解决办法
6400
查看次数