LooperExecutor--实现阻塞等待异步执行

Executor是一个接口,其中只有一个方法

public interface 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
     */
    void execute(Runnable command);
}

Executor存在两个子接口ExecutorService,ScheduledExecutorService;四个实现类AbstractExecutorService,ForkJoinPool,ScheduledThreadPoolExecutor,ThreadPoolExecutor。

ExecutorService:提供了管理终止的方法,以及可以跟踪一个或多个异步任务执行状况而生成 Future 的接口。
ScheduledExecutorService:继承了ExecutorService 接口,提供延时执行或定时执行的方法。
ThreadPoolExecutor:核心实现类,通过类图,我们可以知道,ThreadPoolExecutor是对Executor的拓展,实现,增加了一下新的方法对线程池的管理。
ScheduledThreadPoolExecutor:ThreadPoolExecutor的子类,它可以额外安排命令在给定延迟后运行,或定期执行。

LooperExecutor是继承于 AbstractExecutorService

所以LooperExecutor可以执行FutureTask,可以实现阻塞等待异步结果。

public abstract class AbstractExecutorServiceextends Objectimplements ExecutorService
提供 ExecutorService 执行方法的默认实现。
此类使用包中提供的默认 FutureTask 类实现了 submit、invokeAny 和 invokeAll 方法。
例如,submit(Runnable) 的实现创建了一个相关的 FutureTask 类,该类将被执行并返回。
为了使用不同 Future 实现而重写这些方法的子类,对于每个方法都应该采用一致的做法。
FutureTask 可取消的异步任务,提供Future的基础实现,并实现了Runnable接口。
FutureTask包含了取消与启动计算的方法,查询计算是否完成以及检索计算结果的方法。
只有在计算完成才能检索到结果,调用get()方法时如果任务还没有完成将会阻塞调用线程至到任务完成。
一旦计算完成就不能重新开始与取消计算,但可以调用runAndReset()重置状态后再重新计算。

LooperExecutor是在aosp的Launcher3应用中实现的

LooperExecutor的源码:

/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */
package com.android.launcher3.util;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Process;

import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Extension of {@link AbstractExecutorService} which executed on a provided looper.
 */
public class LooperExecutor extends AbstractExecutorService {

    private final Handler mHandler;

    public LooperExecutor(Looper looper) {
        mHandler = new Handler(looper);
    }

    public Handler getHandler() {
        return mHandler;
    }

    @Override
    public void execute(Runnable runnable) {
        if (getHandler().getLooper() == Looper.myLooper()) {
            runnable.run();
        } else {
            getHandler().post(runnable);
        }
    }

    /**
     * Same as execute, but never runs the action inline.
     */
    public void post(Runnable runnable) {
        getHandler().post(runnable);
    }

    /**
     * Not supported and throws an exception when used.
     */
    @Override
    @Deprecated
    public void shutdown() {
        throw new UnsupportedOperationException();
    }

    /**
     * Not supported and throws an exception when used.
     */
    @Override
    @Deprecated
    public List<Runnable> shutdownNow() {
        throw new UnsupportedOperationException();
    }

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

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

    /**
     * Not supported and throws an exception when used.
     */
    @Override
    @Deprecated
    public boolean awaitTermination(long l, TimeUnit timeUnit) {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns the thread for this executor
     */
    public Thread getThread() {
        return getHandler().getLooper().getThread();
    }

    /**
     * Returns the looper for this executor
     */
    public Looper getLooper() {
        return getHandler().getLooper();
    }

    /**
     * Set the priority of a thread, based on Linux priorities.
     * @param priority Linux priority level, from -20 for highest scheduling priority
     *                to 19 for lowest scheduling priority.
     * @see Process#setThreadPriority(int, int)
     */
    public void setThreadPriority(int priority) {
        Process.setThreadPriority(((HandlerThread) getThread()).getThreadId(), priority);
    }
}

使用LooperExecutor实现阻塞等待异步执行结果

    private void test(){
        try {
            LooperExecutor executor = new LooperExecutor(Looper.getMainLooper());
            executor.submit((Callable<Void>) () -> {
                int i = 1;
                return null;
            }).get();
        } catch (InterruptedException| ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值