好的,这是一个我认为不需要问的问题,但不论是长时间还是其他什么问题,但我的思绪都很模糊,所以就这样了。
使用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
。因此,访问应该是同步的。你会选择哪种方式?使变量变为volatile(以便两个线程都具有最新的本地值),使isRunning
方法同步?或通过synchronized(mRunning){...}
访问变量?
最后,release
方法的实现是按标准执行的吗?或者你选择的任何其他方式?
答案 0 :(得分:1)
如果争用锁定较低,那么同步锁定的成本与易失性访问相同。如果conention很高,那么易失性版本可能会表现得更好。
你不能这样做:
synchronized(mRunning) { ... } //ERROR!
mRunning是一个布尔表达式。您无法在布尔值上进行同步,只能在对象上进行同步。