欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发经验谈:并发编程(线程与线程池)(推荐)

程序员文章站 2023-10-30 14:52:52
一、线程 在android开发中,你不可能都在主线程中开发,毕竟要联网,下载数据,保存数据等操作,当然这就离不开线程。 (当然你可以在android4.0以前的手机里在...

一、线程

在android开发中,你不可能都在主线程中开发,毕竟要联网,下载数据,保存数据等操作,当然这就离不开线程。

(当然你可以在android4.0以前的手机里在主线程请求网络,我最早开发的时候,用的手机比较古老。。。)

在android中你可以随意创建线程,于是就会造成线程不可控,内存泄漏,创建线程消耗资源,线程太多了消耗资源等问题。
具体线程怎么创建我就不在文章里描述了,毕竟这主要将并发编程。。。。

大家知道线程不可控就好了。。。于是就需要对线程进行控制,防止一系列问题出现,这就用到了如下要讲的东西。

二、线程池

线程池:顾名思义,就是放线程的大池子。

如何创建一个线程池?

先说说几个系统的线程池:

  1. fixedthreadpool 创建定长线程的线程池
  2. cachedthreadpool 需要的时候建立新的线程,超时线程销毁
  3. singlethreadpool 单个线程的线程池
  4. scheduledthreadpool 可以定时的线程池,创建周期性的任务

这几个线程池不做多余阐述,因为这些线程池的原理都与我下面要讲的有关。。。。

如何自定义线程池(先来了解几个必须知道的参数):

corepoolsize:

核心线程池大小,线程池中主要工作的线程的多少。

maximumpoolsize:

线程池最大线程数。

keepalivetime:

空闲线程可保持的时间是多久,如果你启用了allowcorethreadtimeout方法,你的线程池里的空闲线程在这个时间段后会自动销毁,如果没启用,则只要不超过corepoolsize,空闲线程也不会销毁。

unit:

keepalivetime的时间单位

workqueue:

阻塞队列,当任务达到corepoolsize,就会被放入这个队列

常见几种blockingqueue实现

  1. arrayblockingqueue :  有界的数组队列
  2. linkedblockingqueue : 可支持有界/*的队列,使用链表实现
  3. priorityblockingqueue : 优先队列,可以针对任务排序
  4. synchronousqueue : 队列长度为1的队列,和array有点区别就是:client thread提交到block queue会是一个阻塞过程,直到有一个worker thread连接上来poll task。

threadfactory:

线程工厂,主要用来创建线程;

handler:

表示当拒绝处理任务时的策略,也就是参数maximumpoolsize达到后丢弃处理的方法。有以下四种取值:

  1. threadpoolexecutor.abortpolicy:丢弃任务并抛出rejectedexecutionexception异常。
  2. threadpoolexecutor.discardpolicy:也是丢弃任务,但是不抛出异常。
  3. threadpoolexecutor.discardoldestpolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
  4. threadpoolexecutor.callerrunspolicy:由调用线程处理该任务

用户也可以实现接口rejectedexecutionhandler定制自己的策略。

代码展示:

//线程工厂
public class taskthreadfactory implements threadfactory {

 private final atomicinteger mthreadnumber = new atomicinteger(1);



 private final string mnameprefix;

 taskthreadfactory(string name) {
  mnameprefix = name + "#";
 }

 public thread newthread(runnable r) {
  thread t = new thread(r,mnameprefix + mthreadnumber.getandincrement());

//  if (t.isdaemon())
//   t.setdaemon(false);
//
//  if (t.getpriority() != thread.norm_priority)
//   t.setpriority(thread.norm_priority);

  return t;
 }
}

//重写runnable
public class prunnable implements runnable {

 public static final int high = 1;//优先级高
 public static final int normal = 2;//优先级中等
 public static final int low = 3;//优先级低
 @intdef({high,normal,low})
 @retention(retentionpolicy.source)
 public @interface priority{}

 public final int priority;
 private final runnable runnable;
 public int serial;

 public prunnable(runnable runnable){
  this(normal,runnable);
 }

 public prunnable(@priority int priority,runnable runnable){
  this.priority = priority;
  this.runnable = runnable;
 }

 @override
 public void run() {
  if (runnable != null) {
   runnable.run();
  }
 }

 /**
  * 线程队列方式 先进先出
  * @param r1
  * @param r2
  * @return
  */
 public static final int comparefifo(prunnable r1, prunnable r2) {
  int result = r1.priority-r2.priority;
  return result==0?r1.serial-r2.serial:result;
 }

 /**
  * 线程队列方式 后进先出
  * @param r1
  * @param r2
  * @return
  */
 public static final int comparelifo(prunnable r1, prunnable r2) {
  int result = r1.priority-r2.priority;
  return result==0?r2.serial-r1.serial:result;
 }
}

//线程池实现
public class taskexecutor implements executor {

 private final static int queue_init_capacity = 20;

 private static final int core = 3;

 private static final int max = 5;

 private static final int timeout = 30 * 1000;

 private atomicinteger serial = new atomicinteger(0);//主要获取添加任务

 public static class config {
  public int core;

  public int max;

  public int timeout;

  public boolean allowcoretimeout;

  public boolean fifo;

  public config(int core, int max, int timeout, boolean allowcoretimeout,boolean fifo) {
   this.core = core;
   this.max = max;
   this.timeout = timeout;
   this.allowcoretimeout = allowcoretimeout;
   this.fifo = fifo;
  }
 }

 public static config defaultconfig = new config(core, max, timeout, true,true);


 private final string name;

 private final config config;

 private executorservice service;

 public taskexecutor(string name) {
  this(name, defaultconfig);
 }

 public taskexecutor(string name, config config) {
  this(name, config, true);
 }

 public taskexecutor(string name, config config, boolean startup) {
  this.name = name;
  this.config = config;

  if (startup) {
   startup();
  }
 }

 public void startup() {
  synchronized (this) {
   if (service != null && !service.isshutdown()) {
    return;
   }

   service = createexecutor(config);
  }
 }

 public void shutdown() {
  executorservice executor = null;

  synchronized (this) {
   // 交换变量
   if (service != null) {
    executor = service;
    service = null;
   }
  }

  if (executor != null) {
   // 停止线程
   if (!executor.isshutdown()) {
    executor.shutdown();
   }

   // 回收变量
   executor = null;
  }
 }

 private void executerunnable(prunnable runnable) {
  synchronized (this) {
   if (service == null || service.isshutdown()) {
    return;
   }
   runnable.serial = serial.getandincrement();
   service.execute(runnable);
  }
 }

 @override
 public void execute(runnable runnable) {
  if (runnable instanceof prunnable) {
   executerunnable((prunnable) runnable);
  }else{
   executerunnable(new prunnable(runnable));
  }
 }

 public future<?> submit(runnable runnable) {
  synchronized (this) {
   if (service == null || service.isshutdown()) {
    return null;
   }
   if (runnable instanceof prunnable) {
    ((prunnable) runnable).serial = serial.getandincrement();
    return service.submit(runnable);
   }else{
    prunnable prunnable = new prunnable(runnable);
    prunnable.serial = serial.getandincrement();
    return service.submit(prunnable);
   }
  }
 }

 public void execute(runnable runnable, @prunnable.priority int priority) {
  executerunnable(new prunnable(priority,runnable));
 }

 private executorservice createexecutor(config config) {
  threadpoolexecutor service = new threadpoolexecutor(config.core, config.max, config.timeout,
    timeunit.milliseconds, new priorityblockingqueue<runnable>(queue_init_capacity, config.fifo ? mqueuefifocomparator : mqueuelifocomparator),
    new taskthreadfactory(name), new threadpoolexecutor.discardpolicy());

  allowcorethreadtimeout(service, config.allowcoretimeout);

  return service;
 }

 public boolean isbusy() {
  synchronized (this) {
   if (service == null || service.isshutdown()) {
    return false;
   }
   if(service instanceof threadpoolexecutor){
    threadpoolexecutor tservice = (threadpoolexecutor) service;
    return tservice.getactivecount() >= tservice.getcorepoolsize();
   }
   return false;
  }
 }

 private static final void allowcorethreadtimeout(threadpoolexecutor service, boolean value) {
  if (build.version.sdk_int >= 9) {
   allowcorethreadtimeout9(service, value);
  }
 }

 @targetapi(9)
 private static final void allowcorethreadtimeout9(threadpoolexecutor service, boolean value) {
  service.allowcorethreadtimeout(value);
 }


 comparator<runnable> mqueuefifocomparator = new comparator<runnable>() {

  @override
  public int compare(runnable lhs, runnable rhs) {
   prunnable r1 = (prunnable) lhs;
   prunnable r2 = (prunnable) rhs;

   return prunnable.comparefifo(r1, r2);
  }
 };

 comparator<runnable> mqueuelifocomparator = new comparator<runnable>() {

  @override
  public int compare(runnable lhs, runnable rhs) {
   prunnable r1 = (prunnable) lhs;
   prunnable r2 = (prunnable) rhs;

   return prunnable.comparelifo(r1, r2);
  }
 };

}

以上所述是小编给大家介绍的android开发经验谈:并发编程(线程与线程池)详解整合,希望对大家有所帮助