android 线程池的管理工具类

这篇具有很好参考价值的文章主要介绍了android 线程池的管理工具类。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

封装了各种类型的线程池,方便直接使用

看下有哪些类型:

默认线程池,搜索模块专用线程池,网络请求专用线程池,U盘更新,同步SDK读写操作线程池,日志打印使用线程池

DEFALUT,SEARCH,NET_WORK,UDISK_DOWNLOAD,SDK_IO,LOG_PRINT

看下有哪些优先级级别

UI_TOP, UI_NORMAL, UI_LOW, DEFAULT, BG_TOP, BG_NORMAL, BG_LOW;

一:实现默认线程池

接下来先实现一个 默认实现 等待队列, 优先级比较,核心线程数等的线程池

开放 核心线程数,线程创建的工厂类(可以定制线程的优先级)供 外部定制(你也可以开放更多的参数)

public class TaskPriorityExecutor implements Executor {

   private static final int CORE_POOL_SIZE = 3;
   private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
   private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
   private static final int KEEP_ALIVE = 30;

   private static final Comparator<Runnable> RUNNABLE_COMPARATOR = new Comparator<Runnable>() {
      @Override
      public int compare(Runnable lhs, Runnable rhs) {
         if (lhs instanceof TaskPriorityRunnable && rhs instanceof TaskPriorityRunnable) {
            return ((TaskPriorityRunnable) lhs).priority.ordinal() - ((TaskPriorityRunnable) rhs).priority.ordinal();
         } else {
            return 0;
         }
      }
   };

   private final BlockingQueue<Runnable> mPoolWorkQueue =
      new PriorityBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE, RUNNABLE_COMPARATOR);
   private final ThreadPoolExecutor mThreadPoolExecutor;

   public TaskPriorityExecutor() {
        this(CORE_POOL_SIZE, new TaskThreadFactory("Defalut"));
    }

   public TaskPriorityExecutor(int poolSize, ThreadFactory threadFactory) {
      mThreadPoolExecutor = new ThreadPoolExecutor(
         poolSize,
         MAXIMUM_POOL_SIZE,
         KEEP_ALIVE,
         TimeUnit.SECONDS,
         mPoolWorkQueue,
            threadFactory);
   }

   /**
    * 该构造器会创建单线程池执行任务
    */
   public TaskPriorityExecutor(ThreadFactory threadFactory) {
      mThreadPoolExecutor = new ThreadPoolExecutor(1, 1,
         0L, TimeUnit.MILLISECONDS,
         new LinkedBlockingQueue<Runnable>(),
         threadFactory);
   }

   public int getPoolSize() {
      return mThreadPoolExecutor.getCorePoolSize();
   }

   public void setPoolSize(int poolSize) {
      if (poolSize > 0) {
         mThreadPoolExecutor.setCorePoolSize(poolSize);
      }
//    Executors.newCachedThreadPool()
//    Executors.newFixedThreadPool()
//    Executors.newScheduledThreadPool()
//    Executors.newSingleThreadExecutor()
//    Executors.newSingleThreadScheduledExecutor()
   }

   public ThreadPoolExecutor getThreadPoolExecutor() {
      return mThreadPoolExecutor;
   }

   /**
    * 线程池忙
    */
   public boolean isBusy() {
      return mThreadPoolExecutor.getActiveCount() >= mThreadPoolExecutor.getCorePoolSize();
   }

   /**
    * 线程池超载
    */
   public boolean isFull() {
      return mThreadPoolExecutor.getActiveCount() >= mThreadPoolExecutor.getCorePoolSize() * 2;
   }

    public boolean isShutdown(){
        return mThreadPoolExecutor.isShutdown();
    }

   @Override
   public void execute(final Runnable r) {
      mThreadPoolExecutor.execute(r);
   }

二 根据接口定制业务场景的线程池接口

接下来我们就开始根据开放的接口来根据不同的业务需要来配置自己的线程池

final class TaskProxy< extends Task<ResultType> {

   private final Task<ResultType> task;
   private Executor executor;

   /*package*/ static final InternalHandler INTERNAL_HANDLER = new InternalHandler();

   static TaskPriorityExecutor sDefaultExecutor = new TaskPriorityExecutor();
   static TaskPriorityExecutor sSearchExecutor = null;
   static TaskPriorityExecutor sNetExecutor = null;
   static TaskPriorityExecutor sAE8EngineExecutor = null;
   static TaskPriorityExecutor sUDiskExecutor = null;
   static TaskPriorityExecutor sTtsInitializeExecutor = null;
   static TaskPriorityExecutor sSyncSdkIOHandleExecutor = null;
   static TaskPriorityExecutor sAdapterExecutor = null;
   static TaskPriorityExecutor sLoggerExecutor = null;
   static TaskPriorityExecutor sActivateLogExecutor = null;

   private ResultType result;
   private Throwable exception;
   private CancelledException cancelledException;

   /*package*/ TaskProxy(Task<ResultType> task) {
      if (task == null) {
         throw new IllegalArgumentException("task must not be null");
      }
      this.task = task;
      this.executor = task.getExecutor();
      if (this.executor == null) {
         this.executor = sDefaultExecutor;
      }
   }

   public static synchronized TaskPriorityExecutor getExecute(TaskExector type){
        if (TaskExector.DEFALUT.equals(type)) {
            if (sDefaultExecutor == null || sDefaultExecutor.isShutdown()){
                sDefaultExecutor = new TaskPriorityExecutor(4, new TaskThreadFactory("Default"));
            }
            return sDefaultExecutor;
        }else if(TaskExector.SEARCH.equals(type)) {
         if (sSearchExecutor == null || sSearchExecutor.isShutdown()){
            sSearchExecutor = new TaskPriorityExecutor(2, new TaskThreadFactory("Search"));
         }
         return sSearchExecutor;
      } else if (TaskExector.NET_WORK.equals(type)){
         if (sNetExecutor == null || sNetExecutor.isShutdown()){
            sNetExecutor = new TaskPriorityExecutor(1, new TaskThreadFactory("Net"));
         }
         return sNetExecutor;
      } else if (TaskExector.AE8_ENGINE.equals(type)){
         if (sAE8EngineExecutor == null || sAE8EngineExecutor.isShutdown()){
            sAE8EngineExecutor = new TaskPriorityExecutor(1, new TaskThreadFactory("AE8_Engine"));
         }
         return sAE8EngineExecutor;
      } else if (TaskExector.UDISK_DOWNLOAD.equals(type)){
         if (sUDiskExecutor == null || sUDiskExecutor.isShutdown()){
            sUDiskExecutor = new TaskPriorityExecutor(1, new TaskThreadFactory("UDISK_DOWNLOAD"));
         }
         return sUDiskExecutor;
      } else if (TaskExector.SYNC_SDK_IO.equals(type)) {
         if (sSyncSdkIOHandleExecutor == null || sSyncSdkIOHandleExecutor.isShutdown()) {
            sSyncSdkIOHandleExecutor = new TaskPriorityExecutor(1, new TaskThreadFactory("SYNC_SDK_IO_HANDLE"));
         }
         return sSyncSdkIOHandleExecutor;
      } else if (TaskExector.USER_BL.equals(type)) {
         if (sSyncSdkIOHandleExecutor == null || sSyncSdkIOHandleExecutor.isShutdown()) {
            sSyncSdkIOHandleExecutor = new TaskPriorityExecutor(1, new TaskThreadFactory("USER_BL"));
         }
         return sSyncSdkIOHandleExecutor;
      }else if (TaskExector.ADAPTER.equals(type)) {
         if (sAdapterExecutor == null || sAdapterExecutor.isShutdown()) {
            sAdapterExecutor = new TaskPriorityExecutor(1, new TaskThreadFactory("ADAPTER"));
         }
         return sAdapterExecutor;
      }
//    else if (TaskExector.LOGGER.equals(type)) {
//       if (sLoggerExecutor == null || sLoggerExecutor.isShutdown()) {
//          //日志问题出于时序考虑只能单线程模型进行执行
//          sLoggerExecutor = new TaskPriorityExecutor(new TaskThreadFactory("LOGGER"));
//       }
//       return sLoggerExecutor;
//    }
      else if (TaskExector.ACTIVATE_LOG.equals(type)) {
         if (sActivateLogExecutor == null || sActivateLogExecutor.isShutdown()) {
            //日志问题出于时序考虑只能单线程模型进行执行
            sActivateLogExecutor = new TaskPriorityExecutor(new TaskThreadFactory("ACTIVATE_LOG"));
         }
         return sActivateLogExecutor;
      }


      return sDefaultExecutor;
   }

   public synchronized static void shutDown(TaskExector type){
        Logger.d("byron", "[TaskProxy] shutDown:= "+ type);
      if (TaskExector.SEARCH.equals(type)) {
         if (sSearchExecutor != null){
            sSearchExecutor.getThreadPoolExecutor().shutdown();
            sSearchExecutor = null;
         }
      } else if (TaskExector.NET_WORK.equals(type)){
         if (sNetExecutor != null){
            sNetExecutor.getThreadPoolExecutor().shutdown();
            sNetExecutor = null;
         }
      } else if (TaskExector.AE8_ENGINE.equals(type)){
         if (sAE8EngineExecutor != null){
            sAE8EngineExecutor.getThreadPoolExecutor().shutdown();
            sAE8EngineExecutor = null;
         }
      } else if (TaskExector.UDISK_DOWNLOAD.equals(type)){
         if (sUDiskExecutor != null){
            sUDiskExecutor.getThreadPoolExecutor().shutdown();
            sUDiskExecutor = null;
         }
      } else if (TaskExector.SYNC_SDK_IO.equals(type)) {
         if (sSyncSdkIOHandleExecutor != null) {
            sSyncSdkIOHandleExecutor.getThreadPoolExecutor().shutdown();
            sSyncSdkIOHandleExecutor = null;
         }
      } else if (TaskExector.USER_BL.equals(type)) {
         if (sSyncSdkIOHandleExecutor != null) {
            sSyncSdkIOHandleExecutor.getThreadPoolExecutor().shutdown();
            sSyncSdkIOHandleExecutor = null;
         }
      }else if (TaskExector.ADAPTER.equals(type)) {
         if (sAdapterExecutor != null) {
            sAdapterExecutor.getThreadPoolExecutor().shutdown();
            sAdapterExecutor = null;
         }
      }
//    else if (TaskExector.LOGGER.equals(type)) {
//       if (sLoggerExecutor != null) {
//          sLoggerExecutor.getThreadPoolExecutor().shutdown();
//          sLoggerExecutor = null;
//       }
//    }
      else if (TaskExector.ACTIVATE_LOG.equals(type)) {
         if (sActivateLogExecutor != null) {
            sActivateLogExecutor.getThreadPoolExecutor().shutdown();
            sActivateLogExecutor = null;
         }
      }

   }

   public static void onDestory(){
        Logger.d("byron", "[TaskProxy] onDestory");
        if(INTERNAL_HANDLER != null){
            INTERNAL_HANDLER.removeCallbacksAndMessages(null);
        }
   }

   @Override
   protected ResultType doBackground() throws Exception {
      this.setState(State.Waiting);
        TaskPriorityRunnable runnable = new TaskPriorityRunnable(
         task.getPriority(),null,
         new Runnable() {
            @Override
            public void run() {
               try {
                  Logger.d("proxy", "taskProxy 1");
                  // trace_start running
                  TaskProxy.this.setState(State.Running);
                  TaskProxy.this.onStart();

                  result = task.doBackground();
                  if (TaskProxy.this.state.get() == State.Cancelled) { // 没有在doBackground过程中取消成功
                     Logger.d("proxy", "taskProxy 1 cancelled");
                     throw new CancelledException("");
                  }
                  TaskProxy.this.setState(State.Finished);
                  TaskProxy.this.onFinished(result);
               } catch (CancelledException cex) {
                  Logger.d("proxy", "taskProxy e1 = {?}", cex);
                  TaskProxy.this.setState(State.Cancelled);
                  TaskProxy.this.onCancelled(cex);
               } catch (Throwable ex) {
                  Logger.d("proxy", "taskProxy e2 = {?}", ex);
                  TaskProxy.this.setState(State.Error);
                  TaskProxy.this.onError(ex, false);
               }
            }
         });
      this.executor.execute(runnable);
      return null;
   }

   @Override
   protected void onFinished(ResultType result) {
      INTERNAL_HANDLER.obtainMessage(MSG_WHAT_ON_FINISH, this).sendToTarget();
   }

   @Override
   protected void onError(Throwable ex, boolean isCallbackError) {
      exception = ex;
      INTERNAL_HANDLER.obtainMessage(MSG_WHAT_ON_ERROR, this).sendToTarget();
   }

   @Override
   protected void onStart() {
      INTERNAL_HANDLER.obtainMessage(MSG_WHAT_ON_START, this).sendToTarget();
   }

   @Override
   protected void onUpdate(int flag, Object... args) {
      INTERNAL_HANDLER.obtainMessage(MSG_WHAT_ON_UPDATE, flag, 0, new ArgsObj(this, args)).sendToTarget();
   }

   @Override
   protected void onCancelled(CancelledException cex) {
      cancelledException = cex;
      INTERNAL_HANDLER.obtainMessage(MSG_WHAT_ON_CANCEL, this).sendToTarget();
   }

   private void setState(State state) {
      this.state.set(state);
      this.task.state.set(state);
   }

   @Override
   public TaskPriority getPriority() {
      return task.getPriority();
   }

   @Override
   public Executor getExecutor() {
      return task.getExecutor();
   }

   // ########################### inner type #############################
   private static class ArgsObj {
      TaskProxy taskProxy;
      Object[] args;

      public ArgsObj(TaskProxy taskProxy, Object[] args) {
         this.taskProxy = taskProxy;
         this.args = args;
      }
   }

   private final static int MSG_WHAT_ON_START = 1;
   private final static int MSG_WHAT_ON_FINISH = 2;
   private final static int MSG_WHAT_ON_ERROR = 3;
   private final static int MSG_WHAT_ON_UPDATE = 4;
   private final static int MSG_WHAT_ON_CANCEL = 5;

   /*package*/ final static class InternalHandler extends Handler {

      private InternalHandler() {
         super(Looper.getMainLooper());
      }

      @SuppressWarnings("unchecked")
      @Override
      public void handleMessage(Message msg) {
         if (msg.obj == null) {
            throw new IllegalArgumentException("msg must not be null");
         }
         TaskProxy taskProxy = null;
         Object[] args = null;
         if (msg.obj instanceof TaskProxy) {
            taskProxy = (TaskProxy) msg.obj;
         } else if (msg.obj instanceof ArgsObj) {
            ArgsObj argsObj = (ArgsObj) msg.obj;
            taskProxy = argsObj.taskProxy;
            args = argsObj.args;
         }
         if (taskProxy == null) {
            throw new RuntimeException("msg.obj not instanceof TaskProxy");
         }

         try {
            switch (msg.what) {
               case MSG_WHAT_ON_START: {
                  taskProxy.task.onStart();
                  break;
               }
               case MSG_WHAT_ON_FINISH: {
                  taskProxy.task.onFinished(taskProxy.result);
                  break;
               }
               case MSG_WHAT_ON_ERROR: {
                  try {
                     taskProxy.task.onError(taskProxy.exception, false);
                  } catch (Throwable ignored) {
                  }
                  break;
               }
               case MSG_WHAT_ON_UPDATE: {
                  taskProxy.task.onUpdate(msg.arg1, args);
                  break;
               }
               case MSG_WHAT_ON_CANCEL: {
                  taskProxy.task.onCancelled(taskProxy.cancelledException);
                  break;
               }
               default: {
                  break;
               }
            }
         } catch (Throwable ex) {
            taskProxy.setState(State.Error);
            if (msg.what != MSG_WHAT_ON_ERROR) {
               taskProxy.task.onError(ex, true);
            } else {
               ex.printStackTrace();
            }
         }
      }
   }
}
这里是包含优先级的线程对应的基类,可以通过线程工厂类 创建一个优先级的线程类
/**
 * 任务线程优先级
 */
public class TaskPriorityRunnable implements Runnable {
   public final TaskPriority priority;
   private final Runnable runnable;
   private String name;
   private String oldThreadName;

   public TaskPriorityRunnable(TaskPriority priority, String name, Runnable runnable) {
      this.priority = priority == null ? TaskPriority.DEFAULT : priority;
      this.runnable = runnable;
      this.name = name == null ? null : new StringBuilder().append("Executor#").append(name).toString();
   }

   @Override
   public final void run() {
      // run会进来多次,防止多次设置线程名称引起问题,故添加对name、oldThreadName判空判断
      if (!TextUtils.isEmpty(name) && TextUtils.isEmpty(oldThreadName)){
         oldThreadName = Thread.currentThread().getName();
         Thread.currentThread().setName(name);
      }
      this.runnable.run();
      // oldThreadName不为空时才进入设置线程名称
      if (!TextUtils.isEmpty(oldThreadName)){
         Thread.currentThread().setName(oldThreadName);
         oldThreadName = null;
      }
   }
}

三:其他相关类

这里面还有一些业务类的封装,这里就不再一一贴出来了(如有人需要,可以整个贴出来)文章来源地址https://www.toymoban.com/news/detail-821794.html

public abstract class Task<ResultType> {

   /*package*/ final AtomicReference<State> state = new AtomicReference<>(State.Null);
   /*package*/ TaskProxy taskProxy = null;

   protected abstract ResultType doBackground() throws Exception;

   protected abstract void onFinished(ResultType result);

   protected abstract void onError(Throwable ex, boolean isCallbackError);

   protected void onStart() {
   }

   protected void onUpdate(int flag, Object... args) {
   }

   protected void onCancelled(CancelledException cex) {
   }

   public final void update(int flag, Object... args) {
      if (taskProxy != null) {
         taskProxy.onUpdate(flag, args);
      }
   }

   public final void cancel() {
      this.state.set(State.Cancelled);
      if (taskProxy != null) {
         taskProxy.cancel();
      }
   }

   public final State getState() {
      return state.get();
   }

   public final boolean isStopped() {
      return this.state.get().value() > State.Running.value();
   }

   public TaskPriority getPriority() {
      return null;
   }

   public Executor getExecutor() {
      return null;
   }

   public static class CancelledException extends RuntimeException {
      public CancelledException(String detailMessage) {
         super(detailMessage);
      }
   }

   public static enum State {
      Null(0), Waiting(1), Running(2), Finished(3), Cancelled(4), Error(5);
      private final int value;

      private State(int value) {
         this.value = value;
      }

      public int value() {
         return value;
      }
   }
}

到了这里,关于android 线程池的管理工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Java可执行命令】(十一)Java 密钥库和证书管理工具keytool:玩转密钥库和证书管理,深入解析keytool工具的应用与技巧~

    Java的 keytool 命令是用于管理和操作Java密钥库( KeyStore )的工具。它的设计目的是为了方便Java开发人员生成、管理和操作数字证书,以及实现对保护资源进行安全访问的加密和身份验证。 🔍 一些相关概念? 密钥库(KeyStore):它是存储密钥和证书的容器,可以包含私钥、公

    2024年02月12日
    浏览(47)
  • Vim 插件应用篇 vim-plug:简洁高效的Vim插件管理工具

    用插件管理插件 Vim-plug 是一个Vim插件管理器,利用异步并行可以快速地安装、更新和卸载插件。它的安装和配置都非常简单,而且在操作过程中会给出很多易读的反馈信息,是一个自由、开源、速度非常快的、并行地安装或更新插件,极简的 vim 插件管理器。 Vim-plug的获取链

    2024年02月09日
    浏览(44)
  • 中文编程开发语言工具应用案例:ps5体验馆计时收费管理系统软件

    ps5体验馆计时收费管理系统软件 软件部分功能: 1、计时计费功能:只需点开始计时即可,时间直观显示 2、商品管理功能:可以管理饮料等商品 3、会员管理功能:支持只用手机号作为卡号使用。 4、定时提醒功能:定时时间可以自由设定,到时间电脑会发出提醒声音,并改

    2024年02月08日
    浏览(48)
  • android中线程池的选择

    线程池是把一个或多个线程通过统一的方式进行调度和重复使用的技术。 避免了因为线程过多而带来使用上的开销。 在安卓开发中,为了更好的性能体验,我们在选择线程池的时候,需要从具体需求来考虑,主要考虑以下几方面: 1、从任务的优先级; 2、任务的执行时间长

    2023年04月23日
    浏览(45)
  • Lattics:一款简单易用、好看强大的「类脑式」知识管理工具,笔记应用与写作软件二合一

    随着数字化时代的到来,越来越多的人意识到 知识管理 的重要性。笔记软件和写作软件作为一种常用的知识管理工具,一直以来备受关注。从最早的印象笔记、有道云、为知笔记、幕布mubu到近几年的思源 Siyuan、熊掌记 Bear、flomo浮墨笔记、石墨、语雀yueque、WPS、Notion、Flow

    2024年02月03日
    浏览(36)
  • 内网穿透的应用-如何使用Docker安装DockerUI可视化管理工具无公网IP远程访问

    DockerUI是一个docker容器镜像的可视化图形化管理工具。DockerUI可以用来轻松构建、管理和维护docker环境。它是完全开源且免费的。基于容器安装方式,部署方便高效,浏览和维护docker单节点或集群节点worker和manager。DockerUI具有易于使用的界面。它不需要记住 docker 指令。只需下

    2024年03月22日
    浏览(62)
  • python------线程池的应用

    在python中经常会使用异步,线程池,进程池,解决io操作,在爬虫中并不建议使用进程池(消耗过大) 目标:会使用线程池 1:导入 我们可以看到了只有在demo1完全运行完毕才会运行demo2,这个时候是单任务 2:基本使用方法 我们可以看到这时候2个线程的一起跑 3:线程池的基本使用步骤  

    2024年02月15日
    浏览(40)
  • Kubernetes 的包管理器工具—— Helm 使用指南:打包、安装和升级 Kubernetes 中的应用程序

    作者:禅与计算机程序设计艺术 Helm 是 Kubernetes 的包管理器工具。Helm 可以帮助用户管理复杂的 Kubernetes 应用,通过 Charts 来打包、安装和升级 Kubernetes 中的应用程序。 1.1.1 Helm 安装 Helm 的下载及安装方式可以查看 官方文档。 1.1.2 Helm 操作命令 Helm 提供了多个子命令用于管理

    2024年02月09日
    浏览(54)
  • Linux 内核线程启动以及内核调用应用层程序

    #include linux/kthread.h //内核线程头文件   static task_struct *test_task; test_task = kthread_run(thread_function, NULL, \\\"test_thread_name\\\"); if(IS_ERR(test_task)) {         pr_err(\\\"test_thread_name create failn\\\"); } static int thread_function(void *arg) {     char *envp[3];     char *argv[3];     int ret= 0;     argv[0] = \\\"/bin/sh\\\";  

    2024年02月12日
    浏览(58)
  • 【ALM工具软件】上海道宁与Perforce为您带来用于整个生命周期的应用程序生命周期管理软件

    Helix ALM是 用于整个生命周期的 应用程序生命周期管理的ALM软件 具有专用于 需求管理(Helix RM)、测试用例管理(Helix TCM) 问题管理(Helix IM)的功能模块 Helix ALM提供了 无与伦比的可追溯性 您将知道是否已测试并满足要求 测试运行是否已通过(或失败) 以及问题是否已解

    2024年02月09日
    浏览(53)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包