废话不多少,用代码做解释吧:
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
}
}
}
}
本文介绍了一个抽象类CancelableThread的实现细节,该类继承了Runnable接口并提供了线程启动与停止的方法。CancelableThread允许通过调用start和stop方法来控制线程的运行状态,并在run方法中实现了线程的具体工作逻辑。
568

被折叠的 条评论
为什么被折叠?



