好的,这是我不认为需要提出的问题,但它是漫长的时间还是什么都没问,但是我的想法很模糊,所以事情就这样了。

使用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);
    }
}


因此,两个线程(主线程和循环程序)都访问mRunning。这样,访问应该同步。您会选择哪种方式?使变量可变(使两个线程都具有最新的本地值),使isRunning方法同步?还是通过synchronized(mRunning){...}访问变量?

最后,release方法的实现是按照标准进行的吗?还是您选择其他方式?

最佳答案

如果锁的争用程度很低,则同步锁的成本将与易失性访问的成本大致相同。如果说服力高,那么易失性版本可能会表现更好。

但您不能这样做:

synchronized(mRunning) { ... }  //ERROR!


mRunning是一个布尔表达式。您不能在布尔值上同步,而只能在对象上同步。

07-26 06:04