当前位置: 移动技术网 > 移动技术>移动开发>Android > 探寻Android的线程问题

探寻Android的线程问题

2019年07月24日  | 移动技术网移动技术  | 我要评论

什么是线程?

线程或者线程执行本质上就是一串命令(也是程序代码),然后我们把它发送给操作系统执行。

multithreaded_process

一般来说,我们的cpu在任何时候一个核只能处理一个线程。多核处理器(目前大多数android设备已经都是多核)顾名思义,就是可以同时处理多线程(通俗地讲就是可以同时处理多件事)。

多核处理与单核多任务处理的实质

上面我说的是一般情况,并不是所有的描述都是一定正确的。因为单核也可以用多任务模拟出多线程。

每个运行在线程中的任务都可以分解成多条指令,而且这些指令不用同时执行。所以,单核设备可以首先切换到线程1去执行指令1a,然后切换到线程2去执行指令2a,接着返回到线程1再去执行1b、1c、1d,然后继续切换到线程2,执行2b、2c等等,以此类推。

这个线程之间的切换十分迅速,以至于在单核的设备中也会发生。几乎所有的线程都在相同的时间内进行任务处理。其实,这都是因为速度太快造成的假象,就像电影《黑客帝国》里的特工brown一样,可以变幻出很多的头和手。

接下来我们来看一些代码。

java核心里的线程

在java中,如果要想做平行任务处理的话,会在runnable里面执行你的代码。可以继承thread类,或者实现runnable接口:

// version 1
public class iamathread extends thread {
  public iamathread() {
    super("iamathread");
  }
 
  @override
  public void run() {
     
// your code (sequence of instructions)
  }
}
// to execute this sequence of instructions in a separate thread.
new iamathread().start();
 
// version 2
public class iamarunnable implements runnable {
  @override
  public void run() {
     
// your code (sequence of instructions)
  }
}
// to execute this sequence of instructions in a separate thread.
iamarunnable myrunnable = new iamarunnable();
new thread(myrunnable).start();
 

这两个方法基本上是一样的。第一个版本是创建一个thread类,第二个版本是需要创建一个runnable对象,然后也需要一个thread类来调用它。

第二个版是通常建议使用的方法。这也是一个很大的主题了,超过了本文的范围,以后会再做讨论。

android上的线程

无论何时启动app,所有的组件都会运行在一个单独的线程中(默认的)——叫做主线程。这个线程主要用于处理ui的操作并为视图组件和小部件分发事件等,因此主线程也被称作ui线程。

如果你在ui线程中运行一个耗时操作,那么ui就会被锁住,直到这个耗时操作结束。对于用户体验来说,这是非常糟糕的!这也就是为什么我们要理解android上的线程机制了。理解这些机制就可以把一些复杂的工作移动到其它的线程中去执行。如果你在ui线程中运行一个耗时的任务,那么很有可能会发生anr(应用无响应),这样用户就会很快地结束掉你的app。

android和java一样,它支持使用java里面的thread类来进行一步任务处理。所以可以轻松地像上面java的例子一样来使用android上的线程,不过那好像还是有点困难。

为什么在android上使用标准java的线程会困难呢?

其实平行任务处理没有想象中的那么简单,你必须在多线程中保证并发,就像伟大的tim bray说的那样:ordinary humans can't do concurrency at scale (or really at all) …

特别对于android来说,以下这些功能就略显臃肿:

异步对于ui线程来说是一个主要的pita(如果你需要在后台线程中向主线程更新界面,那么你就会用到)。 如果屏幕方向或者屏幕配置改变的话,就会出现一些更加奇怪的现象。因为改变屏幕方向,会引起activity重建(所以后台线程就需要去改变被销毁的activity的状态了,而如果后台线程不是在ui线程之上的话,那情况会更加复杂,原因如条件1)。 对于线程池来说,没有默认的处理方式。 取消线程操作需要自定义代码实现。
那么在android上怎么进行任务并发处理呢?

你可能听过一些android上一些常见的名词:

1、handler

这就是我们今天要讨论的详细主题。

2、asynctask

使用asynctask是在android上操作线程最简单的方式,也是最容易出错的方式。

3、intentservice

这种方式需要写更多的代码,但是这是把耗时任务移动到后台的很好的方式,也是我最喜欢的方式。配上使用一个eventbus机制的框架如otto,这样的话实现intentservice就非常简单了。

4、loader

关于处理异步任务,还有很多事情需要做,比如从数据库或者内容提供者那里处理一些数据。

5、service

如果你曾经使用过service的话,你应该知道这里会有一点误区,其中一个常见的误解就是服务是运行在后台线程的。其实不是!看似运行在后台是因为它们不与ui组件关联,但是它们(默认)是运行在ui线程上的……所以默认运行在ui线程上,甚至在上面没有ui部件。

如果想要把服务运行在后台线程中,那么必须自定义一个线程,然后把操作代码都运行在那个线程中(与上面提到的方法很类似)。事实上你应该使用intentservice实现,但是这不是本文讨论的主题。

android上的handler

以下是从android developer documentation for handlers:中摘选的一段话:

> a handler allows you to send and process message and runnable objects associated with a thread's messagequeue. each handler instance is associated with a single thread and that thread's message queue. when you create a new handler, it is bound to the thread/message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

为了更好地了解这个概念,也许你需要去看看什么是message queues。

消息队列

在线程里基本都有一个叫做“消息队列”的东西,它负责线程间通信。这是一种设计模式,所有控制指令或者内容在线程间传递。

消息队列如同它的名字那样,对于线程来说,它就是一个指令队列。这里我们还可以做一些更酷的事:

定时消息和线程在某个时间点才执行。 需要在另一个线程中去添加入队动作,而不是在本线程中。
注意:这里说的“消息”和runnable对象、指令队列的概念是一样的。

回到android上的handler……如果你仔细阅读的话,可以看到文档是这样说的:

> a handler allows you to send and process message and runnable objects associated with a thread's messagequeue.

所以handler可以让你给线程队列发消息:

> each handler instance is associated with a single thread and that thread's message queue.

一个handler对象只能和一个线程关联:

> when you create a new handler, it is bound to the thread / message queue of the thread that is creating it

所以一个handler到底和哪个线程关联呢?就是创造它的线程。

> — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.、

在我们了解这些知识后,请继续看……

小贴士:这里有几点可能你还不知道。每个线程都和一个handler类实例绑定,而且可以和别的线程一起运行,相互通信。

还有一个小建议(如果用过asynctask的话),asynctask内部也是使用handler进行处理的,只是不是运行在ui线程而已,它会提供一个channel来和ui线程通信,使用postexecute方法即可实现。

这还挺酷的,那怎么创建handler呢?

有两种方式:

使用默认的构造方法:new handler()。 使用带参的构造方法,参数是一个runnable对象或者回调对象。
handler里面有什么实用的api吗?

请记住:

handler只是简单往消息队列中发送消息而已(或者使用post方式) 它们有更方便的方法可以帮助与ui线程通信。
如果你现在看看handler的api,可以清楚看到这几个方法:

post postdelayed postattime
代码示例

这里的代码都是很基础的,不过你可以好好看看注释。

示例1:使用handler的“post”方法

public class testactivity extends activity {
 
// ...
// all standard stuff
 
@override
public void oncreate(bundle savedinstancestate) {
 
   
// ...
   
// all standard stuff
 
   
// we're creating a new handler here
   
// and we're in the ui thread (default)
   
// so this handler is associated with the ui thread
  handler mhandler = new handler();
 
   
// i want to start doing something really long
   
// which means i should run the fella in another thread.
   
// i do that by sending a message - in the form of another runnable object
 
   
// but first, i'm going to create a runnable object or a message for this
  runnable mrunnableonseparatethread = new runnable() {
    @override
    public void run () {
 
       
// do some long operation
      longoperation();
 
       
// after mrunnableonseparatethread is done with it's job,
       
// i need to tell the user that i'm done
       
// which means i need to send a message back to the ui thread
 
       
// who do we know that's associated with the ui thread?
      mhandler.post(new runnable(){
        @override
        public void run(){
           
// do some ui related thing
           
// like update a progress bar or textview
           
// ....
        }
      });
 
 
    }
  };
 
   
// cool but i've not executed the mrunnableonseparatethread yet
   
// i've only defined the message to be sent
   
// when i execute it though, i want it to be in a different thread
   
// that was the whole point.
 
  new thread(mrunnableonseparatethread).start();
}
 
}

如果根本就没有handler对象,回调post方法会比较难办。

示例2:使用postdelayed方法

近期本站新介绍的特性中,我每次都要模拟edittext的自动完成功能,每次文字改变后都会触发一个api的调用,从服务器中检索数据。

我想减少app调用api的次数,所以决定使用handler的postdelayed方法来实现这个功能。

本例不针对平行处理,只是关于handler给消息队列发送消息还有安排消息在未来的某一点执行等。

// the below code is inside a textwatcher
// which implements the ontextchanged method
// i've simplified it to only highlight the parts we're
// interested in
 
private long lastchange = 0;
 
@override
public void ontextchanged(final charsequence chars,
             int start, int before, int count) {
 
     
// the handler is spawned from the ui thread
    new handler().postdelayed(
 
       
// argument 1 for postdelated = message to be sent
      new runnable() {
        @override
        public void run() {
 
          if (nochangeintext_inthelastfewseconds()) {
            searchandpopulatelistview(chars.tostring()); 
// logic
          }
        }
      },
 
       
// argument 2 for postdelated = delay before execution
      300);
 
    lastchange = system.currenttimemillis();
}
 
 
private boolean nochangeintext_inthelastfewseconds() {
  return system.currenttimemillis() - lastchange >= 300
}

最后我就把“postattime”这个方法作为联系留给读者们了,掌握handler了吗?如果是的话,那么可以尽情使用线程了。

1. android进程

在了解android线程之前得先了解一下android的进程。当一个程序第一次启动的时候,android会启动一个linux进程和一个主线程。默认的情况下,所有该程序的组件都将在该进程和线程中运行。同时,android会为每个应用程序分配一个单独的linux用户。android会尽量保留一个正在运行进程,只在内存资源出现不足时,android会尝试停止一些进程从而释放足够的资源给其他新的进程使用, 也能保证用户正在访问的当前进程有足够的资源去及时地响应用户的事件。android会根据进程中运行的组件类别以及组件的状态来判断该进程的重要性,android会首先停止那些不重要的进程。按照重要性从高到低一共有五个级别:

前台进程

前台进程是用户当前正在使用的进程。只有一些前台进程可以在任何时候都存在。他们是最后一个被结束的,当内存低到根本连他们都不能运行的时候。一般来说, 在这种情况下,设备会进行内存调度,中止一些前台进程来保持对用户交互的响应。 可见进程
可见进程不包含前台的组件但是会在屏幕上显示一个可见的进程是的重要程度很高,除非前台进程需要获取它的资源,不然不会被中止。 服务进程
运行着一个通过startservice() 方法启动的service,这个service不属于上面提到的2种更高重要性的。service所在的进程虽然对用户不是直接可见的,但是他们执行了用户非常关注的任务(比如播放mp3,从网络下载数据)。只要前台进程和可见进程有足够的内存,系统不会回收他们。 后台进程
运行着一个对用户不可见的activity(调用过 onstop() 方法).这些进程对用户体验没有直接的影响,可以在服务进程、可见进程、前台进 程需要内存的时候回收。通常,系统中会有很多不可见进程在运行,他们被保存在lru (least recently used) 列表中,以便内存不足的时候被第一时间回收。如果一个activity正 确的执行了它的生命周期,关闭这个进程对于用户体验没有太大的影响。 空进程
未运行任何程序组件。运行这些进程的唯一原因是作为一个缓存,缩短下次程序需要重新使用的启动时间。系统经常中止这些进程,这样可以调节程序缓存和系统缓存的平衡。
android 对进程的重要性评级的时候,选取它最高的级别。另外,当被另外的一个进程依赖的时候,某个进程的级别可能会增高。一个为其他进程服务的进程永远不会比被服务的进程重要级低。因为服务进程比后台activity进程重要级高,因此一个要进行耗时工作的activity最好启动一个service来做这个工作,而不是开启一个子进程――特别是这个操作需要的时间比activity存在的时间还要长的时候。例如,在后台播放音乐,向网上上传摄像头拍到的图片,使用service可以使进程最少获取到“服务进程”级别的重要级,而不用考虑activity目前是什么状态。broadcast receivers做费时的工作的时候,也应该启用一个服务而不是开一个线程。

2. 单线程模型

当一个程序第一次启动时,android会同时启动一个对应的主线程(main thread),主线程主要负责处理与ui相关的事件,如用户的按键事件,用户接触屏幕的事件以及屏幕绘图事件,并把相关的事件分发到对应的组件进行处理。所以主线程通常又被叫做ui线程。在开发android应用时必须遵守单线程模型的原则: android ui操作并不是线程安全的并且这些操作必须在ui线程中执行。

2.1 子线程更新ui

android的ui是单线程(single-threaded)的。为了避免拖住gui,一些较费时的对象应该交给独立的线程去执行。如果幕后的线程来执行ui对象,android就会发出错误讯息calledfromwrongthreadexception。以后遇到这样的异常抛出时就要知道怎么回事了!

2.2 message queue

在单线程模型下,为了解决类似的问题,android设计了一个message queue(消息队列), 线程间可以通过该message queue并结合handler和looper组件进行信息交换。下面将对它们进行分别介绍:

1. message
message消息,理解为线程间交流的信息,处理数据后台线程需要更新ui,则发送message内含一些数据给ui线程。

2. handler

handler处理者,是message的主要处理者,负责message的发送,message内容的执行处理。后台线程就是通过传进来的handler对象引用来sendmessage(message)。而使用handler,需要implement 该类的handlemessage(message)方法,它是处理这些message的操作内容,例如update ui。通常需要子类化handler来实现handlemessage方法。

3. message queue

message queue消息队列,用来存放通过handler发布的消息,按照先进先出执行。
每个message queue都会有一个对应的handler。handler会向message queue通过两种方法发送消息:sendmessage或post。这两种消息都会插在message queue队尾并按先进先出执行。但通过这两种方法发送的消息执行的方式略有不同:通过sendmessage发送的是一个message对象,会被handler的handlemessage()函数处理;而通过post方法发送的是一个runnable对象,则会自己执行。

4. looper

looper是每条线程里的message queue的管家。android没有global的message queue,而android会自动替主线程(ui线程)建立message queue,但在子线程里并没有建立message queue。所以调用looper.getmainlooper()得到的主线程的looper不为null,但调用looper.mylooper()得到当前线程的looper就有可能为null。
对于子线程使用looper,api doc提供了正确的使用方法:

class looperthread extends thread { 
 public handler mhandler; 
 
 public void run() { 
  looper.prepare(); //创建本线程的looper并创建一个messagequeue
 
  mhandler = new handler() { 
   public void handlemessage(message msg) { 
    // process incoming messages here 
   } 
  }; 
 
  looper.loop(); //开始运行looper,监听message queue 
 } 
}

这个message机制的大概流程:

1. 在looper.loop()方法运行开始后,循环地按照接收顺序取出message queue里面的非null的message。

2. 一开始message queue里面的message都是null的。当handler.sendmessage(message)到message queue,该函数里面设置了那个message对象的target属性是当前的handler对象。随后looper取出了那个message,则调用该message的target指向的hander的dispatchmessage函数对message进行处理。

在dispatchmessage方法里,如何处理message则由用户指定,三个判断,优先级从高到低:

1) message里面的callback,一个实现了runnable接口的对象,其中run函数做处理工作;

2) handler里面的mcallback指向的一个实现了callback接口的对象,由其handlemessage进行处理;

3) 处理消息handler对象对应的类继承并实现了其中handlemessage函数,通过这个实现的handlemessage函数处理消息。

由此可见,我们实现的handlemessage方法是优先级最低的!

3. handler处理完该message (update ui) 后,looper则设置该message为null,以便回收!

在网上有很多文章讲述主线程和其他子线程如何交互,传送信息,最终谁来执行处理信息之类的,个人理解是最简单的方法——判断handler对象里面的looper对象是属于哪条线程的,则由该线程来执行!
1. 当handler对象的构造函数的参数为空,则为当前所在线程的looper;
2.looper.getmainlooper()得到的是主线程的looper对象,looper.mylooper()得到的是当前线程的looper对象。
现在来看一个例子,模拟从网络获取数据,加载到listview的过程:

public class listprogressdemo extends listactivity { 
 
 @override
 public void oncreate(bundle savedinstancestate) { 
  super.oncreate(savedinstancestate); 
  setcontentview(r.layout.listprogress); 
 
  ((button) findviewbyid(r.id.load_handler)).setonclicklistener(new view.onclicklistener(){ 
 
   @override
   public void onclick(view view) { 
    data = null; 
    data = new arraylist<string>(); 
 
    adapter = null; 
 
    showdialog(progress_dialog); 
    new progressthread(handler, data).start(); 
   } 
  }); 
 } 
 
 @override
 protected dialog oncreatedialog(int id) { 
  switch(id) { 
  case progress_dialog: 
     return progressdialog.show(this, "", 
     "loading. please wait...", true); 
 
  default: return null; 
  } 
 } 
 
 private class progressthread extends thread { 
 
  private handler handler; 
  private arraylist<string> data; 
 
  public progressthread(handler handler, arraylist<string> data) { 
   this.handler = handler; 
   this.data = data; 
  } 
 
  @override
  public void run() { 
   for (int i=0; i<8; i++) { 
    data.add("listitem"); //后台数据处理
    try { 
     thread.sleep(100); 
    }catch(interruptedexception e) { 
      
     message msg = handler.obtainmessage(); 
     bundle b = new bundle(); 
     b.putint("state", state_error); 
     msg.setdata(b); 
     handler.sendmessage(msg); 
      
    } 
   } 
   message msg = handler.obtainmessage(); 
   bundle b = new bundle(); 
   b.putint("state", state_finish); 
   msg.setdata(b); 
   handler.sendmessage(msg); 
  } 
   
 } 
 
 // 此处甚至可以不需要设置looper,因为handler默认就使用当前线程的looper
 private final handler handler = new handler(looper.getmainlooper()) {
 
  public void handlemessage(message msg) { // 处理message,更新listview
   int state = msg.getdata().getint("state"); 
   switch(state){ 
    case state_finish: 
     dismissdialog(progress_dialog); 
     toast.maketext(getapplicationcontext(), 
       "加载完成!", 
       toast.length_long) 
       .show(); 
 
     adapter = new arrayadapter<string>(getapplicationcontext(), 
       android.r.layout.simple_list_item_1, 
       data ); 
        
     setlistadapter(adapter); 
 
     break; 
 
    case state_error: 
     dismissdialog(progress_dialog); 
     toast.maketext(getapplicationcontext(), 
       "处理过程发生错误!", 
       toast.length_long) 
      .show(); 
 
     adapter = new arrayadapter<string>(getapplicationcontext(), 
       android.r.layout.simple_list_item_1, 
       data ); 
        
      setlistadapter(adapter); 
 
      break; 
 
    default: 
 
   } 
  } 
 }; 
 
 
 private arrayadapter<string> adapter; 
 private arraylist<string> data; 
 
 private static final int progress_dialog = 1; 
 private static final int state_finish = 1; 
 private static final int state_error = -1; 
} 

这个例子,我自己写完后觉得还是有点乱,要稍微整理才能看明白线程间交互的过程以及数据的前后变化。随后了解到asynctask类,相应修改后就很容易明白了!

2.3 asynctask

asynctask版:

((button) findviewbyid(r.id.load_asynctask)).setonclicklistener(new view.onclicklistener(){ 
 
 @override
 public void onclick(view view) { 
  data = null; 
  data = new arraylist<string>(); 
 
  adapter = null; 
 
  //显示progressdialog放到asynctask.onpreexecute()里 
  //showdialog(progress_dialog); 
  new progresstask().execute(data); 
 } 
}); 
 
private class progresstask extends asynctask, void, integer> { 
 
/* 该方法将在执行实际的后台操作前被ui thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。*/
@override
protected void onpreexecute() { 
 // 先显示progressdialog
 showdialog(progress_dialog); 
} 
 
/* 执行那些很耗时的后台计算工作。可以调用publishprogress方法来更新实时的任务进度。 */
@override
protected integer doinbackground(arraylist<string>... datas) { 
 arraylist<string> data = datas[0]; 
 for (int i=0; i<8; i++) { 
  data.add("listitem"); 
 } 
 return state_finish; 
} 
 
/* 在doinbackground 执行完成后,onpostexecute 方法将被ui thread调用, 
 * 后台的计算结果将通过该方法传递到ui thread. 
 */
@override
protected void onpostexecute(integer result) { 
 int state = result.intvalue(); 
 switch(state){ 
 case state_finish: 
  dismissdialog(progress_dialog); 
  toast.maketext(getapplicationcontext(), 
    "加载完成!", 
    toast.length_long) 
    .show(); 
 
  adapter = new arrayadapter<string>(getapplicationcontext(), 
    android.r.layout.simple_list_item_1, 
    data ); 
     
  setlistadapter(adapter); 
 
  break; 
   
 case state_error: 
  dismissdialog(progress_dialog); 
  toast.maketext(getapplicationcontext(), 
    "处理过程发生错误!", 
    toast.length_long) 
   .show();
 
  adapter = new arrayadapter<string>(getapplicationcontext(), 
    android.r.layout.simple_list_item_1, 
    data );
 
   setlistadapter(adapter);
 
   break;
 
 default:
 
 }
}

android另外提供了一个工具类:asynctask。它使得ui thread的使用变得异常简单。它使创建需要与用户界面交互的长时间运行的任务变得更简单,不需要借助线程和handler即可实现。

1) 子类化asynctask
2) 实现asynctask中定义的下面一个或几个方法
onpreexecute() 开始执行前的准备工作;
doinbackground(params...) 开始执行后台处理,可以调用publishprogress方法来更新实时的任务进度;
onprogressupdate(progress...) 在publishprogress方法被调用后,ui thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
onpostexecute(result) 执行完成后的操作,传送结果给ui 线程。

这4个方法都不能手动调用。而且除了doinbackground(params...)方法,其余3个方法都是被ui线程所调用的,所以要求:
1) asynctask的实例必须在ui thread中创建;
2) asynctask.execute方法必须在ui thread中调用;

同时要注意:该task只能被执行一次,否则多次调用时将会出现异常。而且是不能手动停止的,这一点要注意,看是否符合你的需求!

在使用过程中,发现asynctask的构造函数的参数设置需要看明白:asynctask
params对应doinbackground(params...)的参数类型。而new asynctask().execute(params... params),就是传进来的params数据,你可以execute(data)来传送一个数据,或者execute(data1, data2, data3)这样多个数据。
progress对应onprogressupdate(progress...)的参数类型;
result对应onpostexecute(result)的参数类型。
当以上的参数类型都不需要指明某个时,则使用void,注意不是void。不明白的可以参考上面的例子,或者api doc里面的例子。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网