好的,这是一个我认为不需要问的问题,但要么是长时间的工作,要么是诸如此类的问题,但我的头脑很模糊,所以就这样吧。
使用 HandlerThread、Looper 和 Handler 创建一个类:
public class MyClass {
//private volatile boolean mRunning = false;
private boolean mRunning = false;
private HandlerThread mHandlerThread = null;
private Handler mMessageHandler = null;
public static final int MESSAGE_START = 1;
public static final int MESSAGE_STOP = 2;
public MyClass() {
mHandlerThread = new HandlerThread("com.test.myclass");
mHandlerThread.start();
mMessageHandler = new MessageHandler(mHandlerThread.getLooper());
}
private class MessageHandler extends Handler {
public MessageHandler(Looper looper) {
super(looper);
}
private void start() {
mRunning = true;
}
private void stop() {
mRunning = false;
}
@Override
public void handleMessage(final Message msg) {
try {
switch (msg.what) {
case MESSAGE_START:
start();
break;
case MESSAGE_STOP:
stop();
break;
default:
throw new RuntimeException("Invalid message: " + msg.what);
}
} catch (RuntimeException e) {
stop();
}
}
}
public void release() {
if (isRunning()) {
stop();
}
// PS: is this a good way to stop HandlerThead/Looper in API =< 17 ?
if (mHandlerThread != null) {
mHandlerThread.quit();
mHandlerThread = null;
}
}
// Should this be a synchronized method
public boolean isRunning() {
return mRunning;
/**
* Or should the variable be synchronized itself?
* synchronized(mRunning) { return mRunning; }
*/
// Or just use a semaphore?
}
public void start() {
mMessageHandler.sendEmptyMessage(MESSAGE_START);
}
public void stop() {
mMessageHandler.sendEmptyMessage(MESSAGE_STOP);
}
}
两个线程(main 和looper mRunning
)都可以访问。因此,访问应该是同步的。你会选择哪种方式?使变量易失(以便两个线程都有最新的本地值),使isRunning
方法同步?或通过访问变量synchronized(mRunning){...}
?
最后,release
方法的实现,是否符合标准?还是你会选择其他方式?