スレッドとスレッドプールに関する注意事項(2)Runnable、Callable、Future、FutureTask

Runnable、Callable、Future、FutureTaskとは何ですか?

前回の記事ではThreadの使用について説明し、Threadを継承するか、Runnableを実装してスレッドを作成できることを発見しました。どちらもRunnableと分離できません。同時に、次の図から、スレッドプールを使用すると呼び出し可能タスクも実行できることがわかりますが、これは何に関係していますか?FutureとFurureTaskについては、以下をご覧ください。

まず、スレッドプールとスレッドが送信できるタスクはRunnableとCallableである
ここに画像の説明を挿入
ことがわかりました。まず、RunnableとCallableとFutureのコードを突き出します。

public interface Runnable {
    public abstract void run();
}
public interface Callable<V> {
    V call() throws Exception;
}
public interface Future<V> {

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

どちらもインターフェースであり、実装する必要のあるメソッドのみがあります。違いは、run()には戻り値がないのに対し、call()は戻り値を持つことができ、例外をスローできることです。

Futureにはrunメソッド呼び出しメソッドはありませんが、タスク検査メソッドは多数あります。メソッド名はメソッドの機能を反映することができ、詳細についてはノートを見れば分かります。

だから

  • Runnableを単独で実装するタスクは、それを実行することです。いつ終了しても、実行されません。
  • Callableを単独で実装するタスクを完了すると、それが間違っているかどうかを伝えることができます。
  • Futureにはrunメソッドの呼び出しメソッドがないため、RunnableおよびCallableと連携して機能を強化します。
    FutureTask
public class FutureTask<V> implements RunnableFuture<V> {

RunnableFutureを実装

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

RunnableFutureはFutureとRunnableを継承しているので、それとFutureTaskの両方をスレッドタスクとして使用でき、上記のステートメントを確認できます。
RunnableFutureはインターフェースであるため、runメソッドは実装されておらず、FutureTaskによって実装されています。

 public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

呼び出し可能オブジェクトのcall()メソッドを実行するために再度実行されることがわかります。このCallableは構築メソッドを通じて渡されます(もちろん、実行可能にすることもできます。他のものは呼び出し可能オブジェクトに変換するのに役立ちます)。したがって、call()メソッドが必要です手動実装方法
。FutureTaskの通常の使用方法を見てみましょう。

public class MyClass {
    public static void main(String[] args) {
        ExecutorService es = Executors.newSingleThreadScheduledExecutor();
        MyCallable myCallable = new MyCallable();

        FutureTask<String> myFutureTask = new FutureTask<String>(myCallable) {

            @Override
            public boolean cancel(boolean b) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            protected void done() {
                super.done();
            }
            @Override
            public boolean isDone() {
                return false;
            }
            @Override
            public String get() throws InterruptedException, ExecutionException {
                return null;
            }

            @Override
            public String get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
                return null;
            }
        };
        es.submit(myFutureTask);
        myFutureTask.cancel(true);

    }
}
class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("正在执行");
        return "执行完毕";
    }
}

数百行のFutureTaskコードをすばやく読み取ることができるので、次のことを理解して、メモリを深めます。悪い点を指摘してください。

元の記事を公開16件 ・いい ね0 訪問数249

おすすめ

転載: blog.csdn.net/weixin_43860530/article/details/105309135