当前位置: 移动技术网 > IT编程>移动开发>Android > Android 多线程处理之多线程详解

Android 多线程处理之多线程详解

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

宝宝眼屎多,幻影英雄,近藤和久

handler.post(r)其实这样并不会新起线程,只是执行的runnable里的run()方法,却没有执行start()方法,所以runnable走的还是ui线程。

1.如果像这样,是可以操作ui,但是run还是走在主线程,见打印出来的log线程名字是main,说明是主线程。

这就是为什么可以直接在run方法里操作ui,因为它本质还是ui线程

handler.post(new runnable(){

  public void run(){

  log.e("当前线程:",thread.currrentthread.getname());//这里打印de结果会是main

  settitle("哈哈");

   }

});

2.通过handlerthread获取到looper却是可以新起线程,但是在这里的run方法里操作ui是不可能的,但是这显然有个缺点,如果你执行多次post(r)方法其实走的还是handlerthread线程。假如你执行5次,n次,其实还是一次并且它们是串行的。假如下载5张图片,你会看到图片是下完第一张,才会去下第二张。

实践证明,只有是拥有主线程looper的handler才可以操作ui,而在主线程操作ui可以在handler的handlermessage()方法中操作ui,也可以在handler的post(r)的run方法里操作ui.

handlerthread ht = new handlerthread("handler thread");

ht.start();

handler = new handler(ht.getlooper());

handler.post(new runnable(){//这里run()方法其实还是在等ht.start()调用

  public void run(){

  log.e("当前线程:",thread.currrentthread.getname());//这里打印的会是handler thread

  settitle("哈哈");//这样必定报错

  //android.view.viewroot$calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views.

   }

});

这样该怎么办呢,呵呵,可以无参构建一个handler。用这个handler来发送消息和处理消息,用上面的handler来开启新线程。

mainhandler = new handler(){

  protecket void handlermessage(message msg){

    settitle("哈哈");//这样就不会报错啦

  }

}

handler.post(new runnable(){//这里run()方法其实还是在等ht.start()调用

  public void run(){

  log.e("当前线程:",thread.currrentthread.getname());//这里打印的会是handler thread

  mainhandler.sendempetmessage();//用mainhandler来发送消息

  //settitle("哈哈");//这样必定报错

  //android.view.viewroot$calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views.

   }

});

打印log:

3.其实第2个方法显得麻烦而且低效,用了2个handler,一个用来发起线程,一个用于处理消息。发起线程的handler必须拥有looper,所以还要实例化一个handerthread;而处理消息的handler则不需要looper,因为它默认拥有主线程的looper,所以可以在这个handler处理ui。

其实可以只需要实例化一个handler,在主线程里构建一个无参的handler,然后由它发送和处理消息。而创建线程的任务就不用handler了,直接用new thread(r).start();然后在r的run()方法里面处理逻辑事务。

用这样的模式下载5张图片,你就可能不会看到图片一张挨着一张展示出来,可能第2张先出来,也可能同时出来3张,5条线程很随机的。

private void loadimagesbythread(final string url,final int id){//通过thread来new 出多个线程 
     
    new thread(new runnable(){ 
 
      @override 
      public void run() { 
        // todo auto-generated method stub 
        log.e("当前线程:", ""+thread.currentthread().getname()); 
        drawable drawable = null; 
        try { 
          drawable = drawable.createfromstream(new url(url).openstream(), "image.gif"); 
        } catch (malformedurlexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } catch (ioexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } 
        message msg = mainhandler.obtainmessage(); 
        msg.what = 2012; 
        msg.arg1 = id; 
        msg.obj = drawable; 
        msg.sendtotarget(); 
         
      } 
       
    }).start(); 
  } 

打印log:

4.asynctask

用异步任务架构多任务模型其实也不是很健壮,得创建多个asynctask实例。一个asynctask仅执行一次,不能重复执行,快餐类的线程,一次用完。

实现asynctask子类,最重要的两个方法,一个是doinbackground(params);一个是onpostexecute(result)。在doinbackground()方法里处理耗时事务,并把结果返回,返回的值将在onpostexecute方法作为参数,然后就可以在onpostexecute()把结果展示在ui上面了。

步骤:

①实例化asynctask:

实例化asynctask然后通过task.exec(pamas);传进去参数,这个参数列表是动态的,可以是一个也可以使多个,长度可变。

  asynctask<params,values,reslut>,第一个参数会传进去这个方法doinbackground(params),第二个参数是数据更新的值,第三个是处理事务返回的结果。

②onpreexecute方法:

这个方法没有参数,也没有返回值,可以在这个方法里,做一些提醒。比如show一个dialog,或者弹个toast告诉用户开始下载啦。

③doinbackground(params)方法:

进入asynctask内部结构,首先将执行reslut doinbackground(params)方法,这个方法将处理耗时事务,exec()的参数将会传进这个方法做参数,而返回值将会作为onpostexecute()的参数。如果要更新进度的话,需执行publicprogress()方法。

④onprogressupdate(values)方法:

这个方法的参数必须在doinbackground()方法里执行publicprogress()方法,这个方法将会把参数传递进onprogressupdate()方法里,然后可以在这个方法做一些ui上的更新展示,比如进度条的值就可以通过这个values值动态改变。

⑤onpostexecute(result)方法:

这里就是事务处理完毕的走的方法,doinbackground方法执行的结果将传到这里,如果这个方法返回了数据。在这个方法里可以处理ui,可以把处理完的数据展示在ui上。比如图片啊,文字啊,一切你想要的结果。

private void loadimagebyasynctask(final string url,final int id){//构建异步任务,这样就不用handler来处理消息了 
    downloadtask task = new downloadtask(); 
    task.execute(""+id,url);//asynctask不可重复执行 
  } 
   
  class downloadtask extends asynctask<string,integer,drawable>{ 
 
    int id; 
    @override 
    protected drawable doinbackground(string... params) {//params保存url和控件id两个数据 
      // todo auto-generated method stub 
      log.e("当前线程:", ""+thread.currentthread().getname()); 
      drawable drawable = null; 
      this.id = integer.parseint(params[0]); 
      try { 
        drawable = drawable.createfromstream(new url(params[1]).openstream(), "image.gif"); 
      } catch (malformedurlexception e) { 
        // todo auto-generated catch block 
        e.printstacktrace(); 
      } catch (ioexception e) { 
        // todo auto-generated catch block 
        e.printstacktrace(); 
      } 
       
      return drawable; 
    } 
 
    @override 
    protected void onpostexecute(drawable result) { 
      // todo auto-generated method stub 
      super.onpostexecute(result); 
      ((imageview)mainactivity.this.findviewbyid(id)).setimagedrawable(result); 
    } 
 
    @override 
    protected void onpreexecute() { 
      // todo auto-generated method stub 
      super.onpreexecute(); 
    } 
 
    @override 
    protected void onprogressupdate(integer... values) { 
      // todo auto-generated method stub 
      super.onprogressupdate(values); 
    } 
 
     
  } 

这里打印的log

 

5.executorservie线程池

通过executors的静态方法来创建,一般有三种:

1.单线程 :executors.newsinglethreadexecutor();

2.固定数量线程 :executors.newfixedthreadpool();

3.动态线程 :executors.newcachedthreadpool();

这里我们用固定5个线程来应用,使用方法是创建executorservice对象,然后执行submit(r)可以发起一个runnable对象。用线程池来管理的好处是,可以保证系统稳定运行,适用与有大量线程,高工作量的情景下使用,假如要展示1000张图片如果创建1000个线程去加载,保证系统会死掉。用线程池就可以避免这个问题,可以用5个线程轮流执行,5个一组,执行完的线程不直接回收而是等待下次执行,这样对系统的开销就可以减小不少。

private void loadimagesbyexecutors(final string url,final int id){ 
    service.submit(new runnable(){ 
       
      @override 
      public void run() { 
        // todo auto-generated method stub 
        log.e("当前线程:", ""+thread.currentthread().getname()); 
         
        try { 
          final drawable drawable = drawable.createfromstream(new url(url).openstream(), "image.gif"); 
          mainhandler.post(new runnable(){ 
 
            @override 
            public void run() {//这将在主线程运行 
              // todo auto-generated method stub 
              ((imageview)mainactivity.this.findviewbyid(id)).setimagedrawable(drawable); 
            } 
          }); 
           
        } catch (malformedurlexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } catch (ioexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } 
         
      } 
       
    }); 
     
  } 

log:

 

其实可能没有说清楚,第一种不算多线程。

1.loadimagesbyhandler()是通过handler.post()方法,构建两个handler进行通信。

2.loadimagesbythread(),这个是直接new thread()发起线程,在主线程的handler处理消息

3.loadimagebyasynctask(),这个用的是异步任务,所有实现在它的内部结构里,可以在里头操作ui.

4.loadimagesbyexecutors()用的是线程池,使得线程可控,保证稳定运行。

其实常用的就是后三种,第二个用法灵活,简单,但不适宜大数量任务;第三个一般适用于单个任务,一次性任务;第四个一般用于大数量,高密度执行的使用情景,比如批量加载图片,批量下载文件等。

看一眼图吧:

全部源码:

package com.bvin.exec; 
 
import java.io.ioexception; 
import java.net.malformedurlexception; 
import java.net.url; 
import java.util.concurrent.executorservice; 
import java.util.concurrent.executors; 
 
import android.app.activity; 
import android.graphics.drawable.drawable; 
import android.os.asynctask; 
import android.os.bundle; 
import android.os.handler; 
import android.os.handlerthread; 
import android.os.message; 
import android.util.log; 
import android.view.view; 
import android.widget.button; 
import android.widget.imageview; 
 
public class mainactivity extends activity { 
  /** called when the activity is first created. */ 
   
  private handler handler ; 
  private button bt; 
  private handler mainhandler = new handler(){ 
 
    @override 
    public void handlemessage(message msg) { 
      // todo auto-generated method stub 
      super.handlemessage(msg); 
      if(msg.what == 2012){ 
        //只要在主线程就可以处理ui  
        ((imageview)mainactivity.this.findviewbyid(msg.arg1)).setimagedrawable((drawable)msg.obj); 
      } 
    } 
     
     
  }; 
   
  private executorservice service = executors.newfixedthreadpool(5); 
   
  @override 
  public void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.main); 
    initviews(); 
    handlerthread ht = new handlerthread("down image thread"); 
    ht.start(); 
    handler = new handler(ht.getlooper()){//如果有了looper那么这个handler就不可以处理ui了 
 
      @override 
      public void handlemessage(message msg) { 
        // todo auto-generated method stub 
        super.handlemessage(msg); 
         
         
      } 
       
    }; 
     
  } 
   
  private void initviews(){ 
     
    bt = (button)findviewbyid(r.id.bt); 
    bt.setonclicklistener(new view.onclicklistener() { 
       
      @override 
      public void onclick(view v) { 
        // todo auto-generated method stub 
        loadimagesbyexecutors("http://news.baidu.com/z/resource/r/image/2012-11-23/23c1625aca99f02c50d8e510383a34e7.jpg",r.id.iv1); 
        loadimagesbyexecutors("http://news.baidu.com/z/resource/r/image/2012-11-23/c4698d97ef6d10722c8e917733c7beb3.jpg",r.id.iv2); 
        loadimagesbyexecutors("http://news.baidu.com/z/resource/r/image/2012-11-23/f332ffe433be2a3112be15f78bff5a40.jpg",r.id.iv3); 
        loadimagesbyexecutors("http://news.baidu.com/z/resource/r/image/2012-11-23/6ff8a9c647a1e80bc602eeda48865d4c.jpg",r.id.iv4); 
        loadimagesbyexecutors("http://news.baidu.com/z/resource/r/image/2012-11-23/f104d069f7443dca52a878d779392874.jpg",r.id.iv5); 
      } 
    }); 
  } 
   
  private void loadimagesbyhandler(final string url,final int id){//通过拥有looper的handler.post(runnable),新建线程 
     
     
    handler.post(new runnable(){//如果handler没有looper那么它就不能构建新线程了 
 
      @override 
      public void run() { 
        // todo auto-generated method stub 
        log.e("当前线程:", ""+thread.currentthread().getname()); 
        drawable drawable = null; 
        try { 
          drawable = drawable.createfromstream(new url(url).openstream(), "image.gif"); 
        } catch (malformedurlexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } catch (ioexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } 
        //systemclock.sleep(2000); 
        //((imageview)mainactivity.this.findviewbyid(id)).setimagedrawable(drawable); 
        message msg = mainhandler.obtainmessage(); 
        msg.what = 2012; 
        msg.arg1 = id; 
        msg.obj = drawable; 
        msg.sendtotarget(); 
      } 
       
    }); 
     
     
  } 
   
  private void loadimagesbythread(final string url,final int id){//通过thread来new 出多个线程 
     
    new thread(new runnable(){ 
 
      @override 
      public void run() { 
        // todo auto-generated method stub 
        log.e("当前线程:", ""+thread.currentthread().getname()); 
        drawable drawable = null; 
        try { 
          drawable = drawable.createfromstream(new url(url).openstream(), "image.gif"); 
        } catch (malformedurlexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } catch (ioexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } 
        message msg = mainhandler.obtainmessage(); 
        msg.what = 2012; 
        msg.arg1 = id; 
        msg.obj = drawable; 
        msg.sendtotarget(); 
         
      } 
       
    }).start(); 
  }  
 
  private void loadimagebyasynctask(final string url,final int id){//构建异步任务,这样就不用handler来处理消息了 
    downloadtask task = new downloadtask(); 
    task.execute(""+id,url);//asynctask不可重复执行 
  } 
   
  private void loadimagesbyexecutors(final string url,final int id){ 
    service.submit(new runnable(){ 
       
      @override 
      public void run() { 
        // todo auto-generated method stub 
        log.e("当前线程:", ""+thread.currentthread().getname()); 
         
        try { 
          final drawable drawable = drawable.createfromstream(new url(url).openstream(), "image.gif"); 
          mainhandler.post(new runnable(){ 
 
            @override 
            public void run() {//这将在主线程运行 
              // todo auto-generated method stub 
              ((imageview)mainactivity.this.findviewbyid(id)).setimagedrawable(drawable); 
            } 
          }); 
           
        } catch (malformedurlexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } catch (ioexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } 
         
      } 
       
    }); 
     
  } 
   
  class downloadtask extends asynctask<string,integer,drawable>{ 
 
    int id; 
    @override 
    protected drawable doinbackground(string... params) {//params保存url和控件id两个数据 
      // todo auto-generated method stub 
      log.e("当前线程:", ""+thread.currentthread().getname()); 
      drawable drawable = null; 
      this.id = integer.parseint(params[0]); 
      try { 
        drawable = drawable.createfromstream(new url(params[1]).openstream(), "image.gif"); 
      } catch (malformedurlexception e) { 
        // todo auto-generated catch block 
        e.printstacktrace(); 
      } catch (ioexception e) { 
        // todo auto-generated catch block 
        e.printstacktrace(); 
      } 
       
      return drawable; 
    } 
 
    @override 
    protected void onpostexecute(drawable result) { 
      // todo auto-generated method stub 
      super.onpostexecute(result); 
      ((imageview)mainactivity.this.findviewbyid(id)).setimagedrawable(result); 
    } 
 
    @override 
    protected void onpreexecute() { 
      // todo auto-generated method stub 
      super.onpreexecute(); 
    } 
 
    @override 
    protected void onprogressupdate(integer... values) { 
      // todo auto-generated method stub 
      super.onprogressupdate(values); 
    } 
 
     
  } 
} 



以上就是对android 多线程的资料整理,后续继续补充相关知识,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网