资讯专栏INFORMATION COLUMN

java并发编程学习之线程池-AbstractExecutorService(二)

Jokcy / 455人阅读

摘要:抽象类,实现了的接口。将任务封装成提交任务主要方法在任务是否超时超时时间任务书用于存放结果的,先完成的放前面。

AbstractExecutorService抽象类,实现了ExecutorService的接口。

newTaskFor

将任务封装成FutureTask

protected  RunnableFuture newTaskFor(Runnable runnable, T value) {
    return new FutureTask(runnable, value);
}
protected  RunnableFuture newTaskFor(Callable callable) {
    return new FutureTask(callable);
}
submit

提交任务

public Future submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}
public  Future submit(Runnable task, T result) {
    if (task == null) throw new NullPointerException();
    RunnableFuture ftask = newTaskFor(task, result);
    execute(ftask);
    return ftask;
}
public  Future submit(Callable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}
invokeAny

主要方法在doInvokeAny

//tasks任务
//timed是否超时
//nanos超时时间
private  T doInvokeAny(Collection> tasks,
                              boolean timed, long nanos)
    throws InterruptedException, ExecutionException, TimeoutException {
    if (tasks == null)
        throw new NullPointerException();
    int ntasks = tasks.size();//任务书
    if (ntasks == 0)
        throw new IllegalArgumentException();
    ArrayList> futures = new ArrayList>(ntasks);
    //用于存放结果的,先完成的放前面。所以第一个任务没完成的时候,会继续提交后续任务
    ExecutorCompletionService ecs =
        new ExecutorCompletionService(this);

    try {     
        //异常信息
        ExecutionException ee = null;
        //过期时间
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        Iterator> it = tasks.iterator();//获取第一个任务
        提交任务
        futures.add(ecs.submit(it.next()));
        --ntasks;//因为提交了一个,任务数-1
        int active = 1;//正在执行的任务

        for (;;) {
            Future f = ecs.poll();
            if (f == null) {//第一个没完成
                if (ntasks > 0) {//还有没提交的任务
                    --ntasks;//任务数-1
                    futures.add(ecs.submit(it.next()));//提交任务
                    ++active;//正在执行的任务+1
                }
                else if (active == 0)//当前没任务了,但是都失败了,异常被捕获了
                    break;
                else if (timed) {
                    f = ecs.poll(nanos, TimeUnit.NANOSECONDS);//等待
                    if (f == null)//返回空,超时抛出异常,结束
                        throw new TimeoutException();
                    nanos = deadline - System.nanoTime();//剩余时间
                }
                else
                    f = ecs.take();//阻塞等待获取
            }
            if (f != null) {//说明已经执行完
                --active;//任务数-1
                try {
                    return f.get();//返回执行结果
                } catch (ExecutionException eex) {
                    ee = eex;
                } catch (RuntimeException rex) {
                    ee = new ExecutionException(rex);
                }
            }
        }

        if (ee == null)
            ee = new ExecutionException();
        throw ee;

    } finally {
        //取消其他任务,毕竟第一个结果已经返回了
        for (int i = 0, size = futures.size(); i < size; i++)
            futures.get(i).cancel(true);
    }
}

public  T invokeAny(Collection> tasks)
    throws InterruptedException, ExecutionException {
    try {
        return doInvokeAny(tasks, false, 0);
    } catch (TimeoutException cannotHappen) {
        assert false;
        return null;
    }
}

public  T invokeAny(Collection> tasks,
                       long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException {
    return doInvokeAny(tasks, true, unit.toNanos(timeout));
}
invokeAll

返回所有任务的结果

public  List> invokeAll(Collection> tasks)
    throws InterruptedException {
    if (tasks == null)
        throw new NullPointerException();
    ArrayList> futures = new ArrayList>(tasks.size());//
    boolean done = false;
    try {
        for (Callable t : tasks) {//封装任务,并提交
            RunnableFuture f = newTaskFor(t);
            futures.add(f);
            execute(f);
        }
        for (int i = 0, size = futures.size(); i < size; i++) {
            Future f = futures.get(i);
            if (!f.isDone()) {
                try {
                    f.get();//阻塞,等待结果
                } catch (CancellationException ignore) {
                } catch (ExecutionException ignore) {
                }
            }
        }
        done = true;
        return futures;
    } finally {
        if (!done)//有异常,取消
            for (int i = 0, size = futures.size(); i < size; i++)
                futures.get(i).cancel(true);
    }
}

public  List> invokeAll(Collection> tasks,
                                     long timeout, TimeUnit unit)
    throws InterruptedException {
    if (tasks == null)
        throw new NullPointerException();
    long nanos = unit.toNanos(timeout);
    ArrayList> futures = new ArrayList>(tasks.size());
    boolean done = false;
    try {
        for (Callable t : tasks)
            futures.add(newTaskFor(t));

        final long deadline = System.nanoTime() + nanos;
        final int size = futures.size();

        // Interleave time checks and calls to execute in case
        // executor doesn"t have any/much parallelism.
        
        for (int i = 0; i < size; i++) {
            execute((Runnable)futures.get(i));
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L)
                return futures;//每个提交都要判断,超时了返回Future
        }

        for (int i = 0; i < size; i++) {
            Future f = futures.get(i);
            if (!f.isDone()) {
                if (nanos <= 0L)
                    return futures;
                try {
                    f.get(nanos, TimeUnit.NANOSECONDS);
                } catch (CancellationException ignore) {
                } catch (ExecutionException ignore) {
                } catch (TimeoutException toe) {
                    return futures;
                }
                nanos = deadline - System.nanoTime();
            }
        }
        done = true;
        return futures;
    } finally {
        if (!done)
            for (int i = 0, size = futures.size(); i < size; i++)
                futures.get(i).cancel(true);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75708.html

相关文章

  • java并发编程习之线程-预定义线程(四)

    摘要:系统预定了几个线程池,不过建议手动创建,以防止错误创建消耗资源,比如创建太多线程或者固定线程数量,无界队列固定线程数量,数量为,无界队列,会按顺序执行不限制线程数量,使用队列,使用于短任务基于用于周期性执行任务示例第一个是,第二个是第一 系统预定了几个线程池,不过建议手动创建,以防止错误创建消耗资源,比如创建太多线程或者OOM FixedThreadPool 固定线程数量,无界队列 p...

    suemi 评论0 收藏0
  • java并发编程习之线程-ThreadPoolExecutor(三)

    摘要:是所有线程池实现的父类,我们先看看构造函数构造参数线程核心数最大线程数线程空闲后,存活的时间,只有线程数大于的时候生效存活时间的单位任务的阻塞队列创建线程的工程,给线程起名字当线程池满了,选择新加入的任务应该使用什么策略,比如抛异常丢弃当前 ThreadPoolExecutor ThreadPoolExecutor是所有线程池实现的父类,我们先看看构造函数 构造参数 corePool...

    阿罗 评论0 收藏0
  • java并发编程习之线程-Executor和ExecutorService(一)

    摘要:接口用于提交任务接口继承了接口设置线程的状态,还没执行的线程会被中断设置线程的状态,尝试停止正在进行的线程当调用或方法后返回为当调用方法后,并且所有提交的任务完成后返回为当调用方法后,成功停止后返回为当前线程阻塞,直到线程执行完时间到被中断 Executor接口 void execute(Runnable command)//用于提交command任务 ExecutorService接...

    liuchengxu 评论0 收藏0
  • java并发编程习之线程的生命周期-start(

    摘要:与执行方法,是用来启动线程的,此时线程处于就绪状态,获得调度后运行方法。执行方法,相对于普通方法调用,在主线程调用。程序是顺序执行的,执行完才会执行下面的程序。 start与run 执行start方法,是用来启动线程的,此时线程处于就绪状态,获得调度后运行run方法。run方法执行结束,线程就结束。 执行run方法,相对于普通方法调用,在主线程调用。程序是顺序执行的,执行完才会执行下...

    bigdevil_s 评论0 收藏0
  • Java线程习(八)线程与Executor 框架

    摘要:一使用线程池的好处线程池提供了一种限制和管理资源包括执行一个任务。每个线程池还维护一些基本统计信息,例如已完成任务的数量。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。使用无界队列作为线程池的工作队列会对线程池带来的影响与相同。 历史优质文章推荐: Java并发编程指南专栏 分布式系统的经典基础理论 可能是最漂亮的Spring事务管理详解 面试中关于Java虚拟机(jvm)的问...

    cheng10 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<