几个任务执行相关的类

Runnable

正面就是Runnable的完整定义,非常简单。

public interface Runnable {
    public abstract void run();
}

Callable

Callable和Runnable的功能非常相似,一样的简捷,但是Callable更强大。
public interface Callable<V> {
    V call() throws Exception;
}
首先说明一点,interface中的方法必然都是抽象方法,"abstract"关键字可以不写。
与Runnable的三点不同:
  1. Callable是基于泛型的,而Runnable不是。
  2. Callable可以返回一个值,而Runnable不可以。
  3. Callable可以抛出异常,而Runnable捕获异常后必须自己处理,不能抛出。

Thread

public class Thread implements Runnable {
    ...
}
启动一个线程要使用start(),而不要去调用run()。stop()、destroy()suspend()、resume()已经废弃不再建议使用了。

Future

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
cancel用于取消任务的执行,取消成功后返回true,然后任务就再也不能被执行了,参数mayInterrupted决定是否让执行任务的线程被中断。

当任务在完成之前被取消则isCancelled返回true。

当任务正常完成、或被取消、或收到异常,则isDone返回true。

get()阻塞直到计算完成,并返回计算结果。

Executor

Executor框架主要是作为线程池来使用的。
public interface Executor {
    void execute(Runnable command);
}

提交给Executor去执行的任务可以是一个Runnable,下面马上可以看到提交给ExecutorService去执行的任务除了Runnable,也可以是Callable。而ExecutorService继承了Executor。

ExecutorService

public interface ExecutorService extends Executor {

    void shutdown();

    List<Runnable> shutdownNow();

    boolean isShutdown();

    boolean isTerminated();

    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    <T> Future<T> submit(Callable<T> task);

    <T> Future<T> submit(Runnable task, T result);

    Future<?> submit(Runnable task);

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                  long timeout, TimeUnit unit)
        throws InterruptedException;

    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;

    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
shutdown是不接收新的任务,但队列中等待的任务还会将它们执行完。shutdownNow是立即强行关闭,并且返回从未开始执行的任务列表。isDhutdown关心Executor是不是shutdown了,而isTerminated关心是不是所有的Tasks已经shutdown了。
awaitTermination将一直阻塞,直到以下3者之一发生:
  1. 调用了shutdown,且所有任务都已结束。
  2. 超时timeout
  3. 抛出异常
submit用于提交一个任务去执行,返回一个Future,通过Future的get()方法来获得任务运行的结果。
InvokeAll提交一组任务,并且返回一组Future。与submit不同,InvokeAll只有当所有任务都完成后才返回--除非调用者线程被中断或者超时,若超时,那么没有被执行的任务将被取消。这样一来,InvokeAll返回的Future列表在调用IsDone时都将返回true。
当Tasks中任意一个完成时,invokeAny就将返回其计算结果,剩下的没有执行完的任务将被取消。注意如果在invokeAny运行期间,collection参数被修改了,那invokeAny返回的结果是不可预知的。

Executors

Executors提供一系列的静态工厂方法用于产生ExecutorSerive、ScheduledExecutorService、ThreadFactory和Callable。

RunnableFuture

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

FutureTask

FutureTask通常用于封装一个Callable或Runnable对象,由于它继承了Runnable,所以它可以交给Executor去执行。它有一个内部类Sync,用于同步控制。
public class FutureTask<V> implements RunnableFuture<V> {
    private final Sync sync;

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        sync = new Sync(callable);
    }

    public FutureTask(Runnable runnable, V result) {
        sync = new Sync(Executors.callable(runnable, result));
    }

    public boolean isCancelled() {
        return sync.innerIsCancelled();
    }

    public boolean isDone() {
        return sync.innerIsDone();
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return sync.innerCancel(mayInterruptIfRunning);
    }

    public V get() throws InterruptedException, ExecutionException {
        return sync.innerGet();
    }

    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        return sync.innerGet(unit.toNanos(timeout));
    }

    protected void done() { }

    protected void set(V v) {
        sync.innerSet(v);
    }

    protected void setException(Throwable t) {
        sync.innerSetException(t);
    }

    public void run() {
        sync.innerRun();
    }

    protected boolean runAndReset() {
        return sync.innerRunAndReset();
    }
}

CompletionService

如果向Excutor提交了一组任务,并且希望在计算完成之后获取结果,需要调用Future的get通过轮询的方法来判断任务是否完成。这种方法有些繁琐。CompletionService将Executor和BlockingQueue整合在一起,可以提交Callable给它执行,然后使用类似于队列操作take()和poll()等方法来获得已完成的结果,而这些结果在完成时被封装为Future。
public interface CompletionService<V> {

    Future<V> submit(Callable<V> task);

    Future<V> submit(Runnable task, V result);

    Future<V> take() throws InterruptedException;

    Future<V> poll();

    Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException;
}
take和poll都将移除队首元素,不同的是:当目前没有任务完成时take将一直阻塞,而poll将立即返回null。
ExecutorCompletionService是CompletionService的具体实现类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值