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

时间:2023-03-08 21:01:50
  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.    private String name;
  11.    private Thread mThread;
  12.    private
    boolean suspendFlag = false;// 控制线程的执行
  13.    // private int i = 0;
  14.    private String TAG = getName();
  15.    /**
  16.     * 构造函数
  17.     * @param name 线程名称。
  18.     * @param suspend 初始化是否暂停。
  19.     */
  20.    public BaseThread(String name, boolean suspend) {
  21.       suspendFlag = suspend;
  22.       this.name = name;
  23.       mThread = new Thread(this, name);
  24.       System.out.println("new Thread: " + mThread);
  25.       mThread.start();
  26.    }
  27.    public
    void run() {
  28.       try {
  29.          while (true) {
  30.             // System.out.println(name + ": " + i++);
  31.             synchronized (this) {
  32.                while (suspendFlag) {
  33.                   wait();
  34.                }
  35.             }
  36.             Thread.sleep(SUSPEND_TIME_MILLISECONDS);
  37.             process();
  38.          }
  39.       } catch (InterruptedException e) {
  40.          e.printStackTrace();
  41.          onDestory();
  42.       }
  43.       Log.i(TAG, name + " exited");
  44.    }
  45.    /**
  46.     * 线程处理接口。
  47.     */
  48.    public
    abstract
    void process();
  49.    /**
  50.     * 线程暂停
  51.     */
  52.    public
    void suspend() {
  53.       this.suspendFlag = true;
  54.    }
  55.    /**
  56.     * 唤醒线程
  57.     */
  58.    public
    synchronized
    void resume() {
  59.       this.suspendFlag = false;
  60.       notify();
  61.    }
  62.    /**
  63.     * 返回线程名
  64.     *
  65.     * @return name
  66.     */
  67.    public String getName() {
  68.       return name;
  69.    }
  70.    /**
  71.     * 获取线程对象。
  72.     *
  73.     * @return 线程对象。
  74.     */
  75.    public Thread getT() {
  76.       return mThread;
  77.    }
  78.    /**
  79.     * 停止线程运行。
  80.     */
  81.    public
    void stop() {
  82.       if (mThread != null){
  83.          mThread.interrupt();
  84.          mThread = null;
  85.       }
  86.    }
  87.    /**
  88.     * 线程处理接口。
  89.     */
  90.    public
    void onDestory()
  91.    {
  92.       Log.i(TAG, name + " destory!");
  93.    }
  94. }