Java高并发编程之 Executor

# Executor接口

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

public class MyExecutor implements Executor {
    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     *                                    accepted for execution
     * @throws NullPointerException       if command is null
     */
    @Override
    public void execute(Runnable command) {
        command.run();
    }

    public static void main(String[] args) {
        new MyExecutor().execute(()-> System.out.println("command.run();"));
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# Callable接口

线程有返回值使用Callable接口,没有返回值使用Runable接口。

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 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;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# Executors

工厂和工具方法:[Executor](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/Executor.html)[ExecutorService](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/ExecutorService.html)[ScheduledExecutorService](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/ScheduledExecutorService.html)[ThreadFactory](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/ThreadFactory.html)[Callable](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/Callable.html)

在此包中定义的类。 该类支持以下几种方法:

  • 创建并返回一个[ExecutorService](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/ExecutorService.html)设置的常用的配置设置的方法。
  • 创建并返回一个[ScheduledExecutorService的](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/ScheduledExecutorService.html)方法, 其中设置了常用的配置设置。
  • 创建并返回“包装”ExecutorService的方法,通过使实现特定的方法无法访问来禁用重新配置。
  • 创建并返回将新创建的线程设置为已知状态的[ThreadFactory的](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/ThreadFactory.html)方法。
  • 创建并返回一个方法[Callable](http://www.matools.com/file/manual/jdk_api_1.8_google/java/util/concurrent/Callable.html)出的其他闭包形式,这样他们就可以在需要的执行方法使用Callable 。

# Future

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

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;
}
1
2
3
4
5
6
7
8
  • cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
  • isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。
  • isDone方法表示任务是否已经完成,若任务完成,则返回true;
  • get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
  • get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
  • 也就是说Future提供了三种功能:
    • 1)判断任务是否完成;
    • 2)能够中断任务;
    • 3)能够获取任务执行结果。

因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了FutureTask。FutureTask是Future接口的一个唯一实现类

上次更新: 2020/08/01, 14:08:00
最近更新
01
RabbitMQ简介
10-27
02
聊聊Java多态
10-21
03
JVM垃圾回收器
10-16
更多文章>