Android程式設計 - 如何中止Thread

来自http://nkeegamedev.blogspot.jp/2013/05/android-thread.html

找了一些blog,看下来只有这个还行。

程式中時需要使用multithread進行背景作業, 但記得必須在程式結束前中止Thread。
查閱文件會發現不論destroy()方法或stop()方法都已聲明不應用來終止thread,而interrupt()方法也並不是用來終止thread。那麼到底該如何正確在應用程式結束時一併終止所建立的Thread,正確的作法是使用interrupt()方法並配合shared variable控制


  boolean RUN_THREAD = true;
  ...


   ocrThread =  new Thread(){
     public  void run(){
        while ( RUN_THREAD){
          //執行緒作業
       }
    }
  };
   ocrThread.start();
  ...
  protected  void onDestroy() {
       RUN_THREAD =  false;
       ocrThread.interrupt();
       ocrThread =  null;
  } 

来自这篇blog讲解也不错http://blog.csdn.net/zhangtengyuan23/article/details/50535813

1、正常关闭:推荐使用业务标志位结束线程的工作流程,待线程工作结束自行关闭, 如下 mWorking 进行控制线程的业务是否继续进行:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * start thread running 
  3.  */  
  4. public void start() {  
  5.     mWorking = true;  
  6.     if (mThread != null && mThread.isAlive()) {  
  7.         if (DEBUG) {  
  8.             LogHelper.i(TAG, "start: thread is alive");  
  9.         }  
  10.     } else {  
  11.         mThread = new Thread(new Runnable() {  
  12.             @Override  
  13.             public void run() {  
  14.                 int interval = 1000 / FRAMES;  
  15.                 while (mWorking) {  
  16.                     moveCircularly();  
  17.                     moveToPercent();  
  18.                     postInvalidate();  
  19.                     SystemClock.sleep(interval);  
  20.                 }  
  21.                 if (DEBUG) {  
  22.                     LogHelper.i(TAG, "run: thread stopping");  
  23.                 }  
  24.             }  
  25.         });  
  26.         mThread.start();  
  27.     }  
  28. }  
  29.   
  30. /** 
  31.  * stop thread running 
  32.  */  
  33. public void stop() {  
  34.     if (mWorking) {  
  35.         mWorking = false;  
  36.     }  
  37. }  



2、暴力型(不推荐):一般不使用这种方法关闭线程,Thread.interrupt() 较暴力,虽然进行 
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. mThread.interrupt();  
  2. mThread = null;  
终止了线程,但查看源码我们发现:
interrupt() 使线程接受一个终端请求,接下来的线程操作有线程当前状态决定。
  • 线程在 wait(), join() 或 sleep() 状态下,它将被唤醒,被清除状态让后会收到一个InterruptedException的 Exception,线程中断 Exception 处理.结束工作。
  • 线程 blocked 在I/ O操作时,会接收ClosedByInterruptException。同样的,该信道将被关闭,线程结束工作。
  • 线程 blocked在Selector 时会立即中断重置状态  return。此情况下,不接收异常。




[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * start running 
  3.  */  
  4. public void start() {  
  5.     mWorking = true;  
  6.     if (mThread != null && mThread.isAlive()) {  
  7.         if (DEBUG) {  
  8.             LogHelper.i(TAG, "start: thread is alive");  
  9.         }  
  10.     } else {  
  11.         mThread = new Thread(new Runnable() {  
  12.             @Override  
  13.             public void run() {  
  14.                 int interval = 1000 / FRAMES;  
  15.                 while (mWorking) {  
  16.                     moveCircularly();  
  17.                     moveToPercent();  
  18.                     postInvalidate();  
  19.                     SystemClock.sleep(interval);  
  20.                 }  
  21.             }  
  22.         });  
  23.         mThread.start();  
  24.     }  
  25. }  
  26.   
  27. public void stop() {  
  28.     if (mWorking) {  
  29.         if (mThread != null && mThread.isAlive()) {  
  30.             mThread.interrupt();  
  31.             mThread = null;  
  32.         }  
  33.         mWorking = false;  
  34.     }  
  35. }  

其实,项目中会集成个性化的线程池,保证不开启过多的线程进行多线程操作(硬件层CPU 支持的核心数有限,过多的线程只能更加分割 cpu 时间片,无法达到更好的效果),也会有自己的新线程创建、管理和结束操作。
在工作中我们将Android Thread分两种线程进行管理,即  UI Thread (最多 Thread 数由 cpu 核心数决定)和 Bkg Thread (最大Thread数为1). 
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private ThreadPoolExecutor mUiThreadPoolExecutor;  
  2. private ThreadPoolExecutor mBkgThreadPoolExecutor;  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private int getUiInitialThreadPoolSize() {  
  2.     int cpuCores = Runtime.getRuntime().availableProcessors();  
  3.     return Math.max(2, cpuCores / 2); // at least 2, or (cores/2)  
  4. }  
 分别进行线程池管理 
 

我们只进行 addTask 进行ThreadFactory new adding thread. 而不强行进行 thread 的关闭处理,由线程业务结束自行结束线程。

先写到这里,更多关于线程方面的知识以后可以多多交流。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值