Android中的java层的线程暂停和恢复实现

  1. /**
  2.  * 基础线程对象.
  3.  *
  4.  * @author jevan
  5.  * @version (1.0 at 2013-6-17)
  6.  * @version (1.1 at 2013-7-2) 增加onDestory接口{@link #onDestory()},增加stop方法{@link #stop() }。
  7.  */
  8. public abstract class BaseThread implements Runnable {
  9.    public static final int SUSPEND_TIME_MILLISECONDS = 50;
  10.  
  11.    private String name;
  12.    private Thread mThread;
  13.  
  14.    private boolean suspendFlag = false;// 控制线程的执行
  15.    // private int i = 0;
  16.    private String TAG = getName();
  17.  
  18.    /**
  19.     * 构造函数
  20.     * @param name 线程名称。
  21.     * @param suspend 初始化是否暂停。
  22.     */
  23.    public BaseThread(String name, boolean suspend) {
  24.       suspendFlag = suspend;
  25.       this.name = name;
  26.       mThread = new Thread(this, name);
  27.       System.out.println("new Thread: " + mThread);
  28.       mThread.start();
  29.    }
  30.  
  31.    public void run() {
  32.       try {
  33.          while (true) {
  34.             // System.out.println(name + ": " + i++);
  35.             synchronized (this) {
  36.                while (suspendFlag) {
  37.                   wait();
  38.                }
  39.             }
  40.             Thread.sleep(SUSPEND_TIME_MILLISECONDS);
  41.             process();
  42.          }
  43.       } catch (InterruptedException e) {
  44.          e.printStackTrace();
  45.          onDestory();
  46.       }
  47.       Log.i(TAG, name + " exited");
  48.    }
  49.  
  50.    /**
  51.     * 线程处理接口。
  52.     */
  53.    public abstract void process();
  54.  
  55.    /**
  56.     * 线程暂停
  57.     */
  58.    public void suspend() {
  59.       this.suspendFlag = true;
  60.    }
  61.  
  62.    /**
  63.     * 唤醒线程
  64.     */
  65.    public synchronized void resume() {
  66.       this.suspendFlag = false;
  67.       notify();
  68.    }
  69.  
  70.    /**
  71.     * 返回线程名
  72.     *
  73.     * @return name
  74.     */
  75.    public String getName() {
  76.       return name;
  77.    }
  78.  
  79.    /**
  80.     * 获取线程对象。
  81.     *
  82.     * @return 线程对象。
  83.     */
  84.    public Thread getT() {
  85.       return mThread;
  86.    }
  87.  
  88.    /**
  89.     * 停止线程运行。
  90.     */
  91.    public void stop() {
  92.       if (mThread != null){
  93.  
  94.          mThread.interrupt();
  95.          mThread = null;
  96.       }
  97.    }
  98.  
  99.    /**
  100.     * 线程处理接口。
  101.     */
  102.    public void onDestory()
  103.    {
  104.       Log.i(TAG, name + " destory!");
  105.    }
  106.  
  107. }

  

原文地址:https://www.cnblogs.com/jevan/p/3141885.html