android(java)里面完全中断(结束)一个正在运(执)行的线程

来源:互联网 发布:美女直播软件 编辑:程序博客网 时间:2024/05/16 09:36

废话不多少,用代码做解释吧:

public abstract class CancelableThread implements Runnable {    private volatile boolean mStopped;    private Thread mThread;    private Context mContext;    private Handler mHandler;    public CancelableThread(Context c, Handler handler) {        mContext = c.getApplicationContext();        mHandler = handler;    }    public void start() {        if (mThread == null) {            mStopped = false;            mThread = new Thread(this, "CancelableThread");            mThread.start();        }    }    public void stop() {        if (mThread != null) {            mStopped = true;            mThread.interrupt();            mThread = null;        }    }    protected abstract void doWork(Context c, Handler handler);    @Override    public void run() {        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);        while (!mStopped) {            try {                doWork(mContext, mHandler);                mStopped = true;                Thread.sleep(10);            } catch (InterruptedException e) {                // Ignore            }        }    }}



原创粉丝点击