最近在做一个项目,在网络请求时考虑用Handler进行处理,然后就研究了一下Handler和Runnable

首先在看一下java中的Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.

In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

这个官方文档中的描述,看原版文档还是很有好处的,就不翻译了。

在Java中Runnable可以实现资源共享的多线程,网上多拿卖票的例子来讲,但是看上去有点模糊不清,对于这样一个代码

  1. MyRunnable runnable = new MyRunnable
  2. new Thread(runnable,"a").start();
  3. new Thread(runnable,"b").start();

它们之间资源共享到底是怎么个共享呢?

现在我们来看一下例子

  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. new Main().test();
  5. }
  6.  
  7. void test(){
  8. MyRunnable runnable = new MyRunnable();
  9. new Thread(runnable,"a").start();
  10. new Thread(runnable,"b").start();
  11. }
  12. public class MyRunnable implements Runnable{
  13. @Override
  14. public void run() {
  15. for (int i=0;i<5;i++) {
  16. System.out.println(Thread.currentThread().getName() + i);
  17. }
  18. }
  19.  
  20. }
  21. }

执行结果

a0
b0
b1
b2
b3
b4
a1
a2
a3
a4

可以看到这两个线程相互之间并没有影响得都执行了5次

然后在我们的Runnable类里边加一个全局变量

  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. new Main().test();
  5. }
  6.  
  7. void test(){
  8. MyRunnable runnable = new MyRunnable();
  9. new Thread(runnable,"a").start();
  10. new Thread(runnable,"b").start();
  11. }
  12.  
  13. public class MyRunnable implements Runnable{
  14. int num=0;
  15. @Override
  16. public void run() {
  17. for (int i=0;i<5;i++) {
  18. ++num;
  19. System.out.println(Thread.currentThread().getName() + i+"--------"+num);
  20. }
  21. }
  22. }
  23. }

执行结果

b0--------2
b1--------3
a0--------2
b2--------4
a1--------5
b3--------6
a2--------7
b4--------8
a3--------9
a4--------10

可以发现这个全局变量是在两个线程之间共享的

这说明什么?当一个Runnable对象传递到多个线程执行时,Runnable对象的run()方法会在多个线程中执行,而全局变量是在这些线程中共享的

因此,我们可以通过一个全局变量充当线程锁比如:

  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. new Main().test();
  5. }
  6.  
  7. void test(){
  8. MyRunnable runnable = new MyRunnable();
  9. new Thread(runnable,"a").start();
  10. new Thread(runnable,"b").start();
  11. }
  12.  
  13. public class MyRunnable implements Runnable{
  14. int num=0;
  15. final String string ="";
  16. @Override
  17. public void run() {
  18. synchronized (string){
  19. for (int i=0;i<5;i++) {
  20. ++num;
  21. System.out.println(Thread.currentThread().getName() + i+"--------"+num);
  22. }
  23. }
  24. }
  25. }
  26. }

这样的执行结果

a0--------1
a1--------2
a2--------3
a3--------4
a4--------5
b0--------6
b1--------7
b2--------8
b3--------9
b4--------10

这样只有当一个线程中的run()方法执行完之后才会执行另一个

然后把同步锁的地方变一下

  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. new Main().test();
  5. }
  6.  
  7. void test() {
  8. MyRunnable runnable = new MyRunnable();
  9. new Thread(runnable, "a").start();
  10. new Thread(runnable, "b").start();
  11. }
  12.  
  13. public class MyRunnable implements Runnable {
  14. int num = 0;
  15. final String string = "";
  16. @Override
  17. public void run() {
  18. for (int i = 0; i < 5; i++) {
  19. synchronized (string) {
  20. ++num;
  21. System.out.println(Thread.currentThread().getName() + i + "--------" + num);
  22. }
  23. }
  24. }
  25. }
  26. }

执行结果

a0--------1
b0--------2
b1--------3
b2--------4
b3--------5
b4--------6
a1--------7
a2--------8
a3--------9
a4--------10

可以看到,两个线程交替执行,但只有一个线程的

  1. ++num;
  2.  
  3. System.out.println(Thread.currentThread().getName() + i + "--------" + num);

执行完之后才会执行另一个线程的,所以全局变量的值是依次增加的。


再来看Android中的Handler的post(Runnale)这个方法

  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. Handler handler = new Handler();
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. MyRunnable myRunnable = new MyRunnable();
  9. handler.post(myRunnable);
  10. }
  11.  
  12. class MyRunnable implements Runnable{
  13. @Override
  14. public void run() {
  15. for (int i=0;i<5;++i){
  16. System.out.println(Thread.currentThread().getName()+"---"+i);
  17. }
  18. }
  19. }
  20. }

可以看到,这个Runnable实在主线程上运行的,因为Handler是在主线程上创建的,与主线程绑定。一些新手可能就会以为这样是新建了一个线程,把耗时操作放里边造成UI卡顿。api说明如下:

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

那么我们post两个呢,代码修改为

  1. MyRunnable myRunnable = new MyRunnable();
  2. handler.post(myRunnable);
  3. handler.post(myRunnable);

那相应的结果

可以看到是依次运行的,这也体现了Handler的消息队列的思想

再改一下

  1. MyRunnable myRunnable = new MyRunnable();
  2. handler.post(myRunnable);
  3. handler.post(myRunnable);
  4. System.out.println("post finish");

可以看到在post之后并不是立即执行。

那么如何post一个runnable对象到子线程执行呢?这就要将Handler与一个子线程绑定

  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. HandlerThread thread = new HandlerThread("subThread");
  4. Handler handler = null;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. thread.start();
  10. handler = new Handler(thread.getLooper());
  11. MyRunnable myRunnable = new MyRunnable();
  12. handler.post(myRunnable);
  13. System.out.println("post finish");
  14. }
  15.  
  16. class MyRunnable implements Runnable{
  17. @Override
  18. public void run() {
  19. for (int i=0;i<5;++i){
  20. System.out.println(Thread.currentThread().getName()+"---"+i);
  21. }
  22. }
  23. }
  24. }

执行结果:

android中的Handler和Runnable的更多相关文章

  1. 深入源代码解析Android中的Handler,Message,MessageQueue,Looper

    本文主要是对Handler和消息循环的实现原理进行源代码分析.假设不熟悉Handler能够參见博文< Android中Handler的使用>,里面对Android为何以引入Handler机 ...

  2. Android中使用Handler造成内存泄露的分析和解决

    什么是内存泄露?Java使用有向图机制,通过GC自动检查内存中的对象(什么时候检查由虚拟机决定),如果GC发现一个或一组对象为不可到达状态,则将该对象从内存中回收.也就是说,一个对象不被任何引用所指向 ...

  3. Android中使用Handler造成内存泄露

    1.什么是内存泄露? Java使用有向图机制,通过GC自动检查内存中的对象(什么时候检查由虚拟机决定),如果GC发现一个或一组对象为不可到达状态,则将该对象从内存中回收.也就是说,一个对象不被任何引用 ...

  4. Android中的Handler的机制与用法详解

    概述: 很多android初学者对android 中的handler不是很明白,其实Google参考了Windows的消息处理机制, 在Android系统中实现了一套类似的消息处理机制.在下面介绍ha ...

  5. Android中利用Handler实现消息的分发机制(三)

    在第二篇文章<Android中利用Handler实现消息的分发机制(一)>中,我们讲到主线程的Looper是Android系统在启动App的时候,已经帮我们创建好了,而假设在子线程中须要去 ...

  6. 转:Android中的Handler的机制与用法详解

    注:Message类的用法: message的几个参数都可以携带数据,其中arg1与arg2可以携带int类型,what是用户自定义的int型,这样接受者可以了解这个消息的信息. 说明:使用Messa ...

  7. Android中关于Handler的若干思考

    在之前的博文中,讲过一些和Handler有关的知识,例如: Android 多线程----AsyncTask异步任务详解 Android多线程----异步消息处理机制之Handler详解 今天再把Ha ...

  8. 深入探索Android中的Handler

    一.概述 1. 什么是Handler Handler是Android消息机制的上层接口,它为我们封装了许多底层的细节,让我们能够很方便的使用底层的消息机制.Handler的最常见应用场景之一便是通过H ...

  9. Android中的Handler的具体用法

    Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行.Android利用Handler来实现UI线程的更新的. Handler是Android中的消息发送器,其在哪个Activit ...

随机推荐

  1. 关于考虑浏览器兼容性时间的工具demo

    //支持跨浏览器的添加事件. var btn = document.getElementById("btn"); function showMes() { alert(" ...

  2. Telerik_2012_Q3 破解全套下载链接

    1.Telerik_OpenAccess_ORM_2012_3_1012_SDK.zip (暂未提供下载) 2. Telerik_OpenAccess_ORM_2012_3_1012.zip 3. T ...

  3. JQUERY 键盘事件

    一 一.首先需要知道的是: 1.keydown()keydown 事件会在键盘按下时触发. 2.keypress()keypress 事件会在敲击按键时触发,我们可以理解为按下并抬起同一个按键. 3. ...

  4. JQuery解析XML数据的几个例子

    用JavaScript解析XML数据是常见的编程任务,JavaScript能做的,JQuery当然也能做.下面我们来总结几个使用JQuery解析XML的例子. 第一种方案: <script ty ...

  5. NYOJ 540

    为了给学弟学妹讲课,我水了一道题…… import java.util.Arrays; import java.util.Scanner; public class NYOJ540 { public ...

  6. 修改weblogic jvm启动参数

    进入: D:\Oracle\Middleware\user_projects\domains\base_domain\startWebLogic.cmd 在call 上一行增加: set USER_M ...

  7. CELL_PHOTO_IDENTIFIER

    # define CELL_PHOTO_IDENTIFIER @"photoLibraryCell" # define CLOSE_PHOTO_IMAGE @"close ...

  8. 温习H3C S5500的VLAN配置

    这,才是我想要的... ACCESS还是TRUNK TYPE?

  9. Struts2之ajax初析

    Web2.0的随波逐流,Ajax那是大放异彩,Struts2框架自己整合了对Ajax的原生支持(struts 2.1.7+,之前的版本可以通过插件实现),框架的整合只是使得JSON的创建变得异常简单, ...

  10. 字符串(多串后缀自动机):HDU 4436 str2int

    str2int Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)Total S ...