Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

线程同步问题 #157

Open
xchengDroid opened this issue Apr 25, 2021 · 4 comments
Open

线程同步问题 #157

xchengDroid opened this issue Apr 25, 2021 · 4 comments

Comments

@xchengDroid
Copy link

private void bindServiceSync() {
        checkRuntime(true);

//        BluetoothLog.v(String.format("bindServiceSync"));

        mCountDownLatch = new CountDownLatch(1);

        Intent intent = new Intent();
        intent.setClass(mContext, BluetoothService.class);

        if (mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)) {
//            BluetoothLog.v(String.format("BluetoothService registered"));
            waitBluetoothManagerReady();
        } else {
//            BluetoothLog.v(String.format("BluetoothService not registered"));
            mBluetoothService = BluetoothServiceImpl.getInstance();
        }
    }

    private final ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            BluetoothLog.v(String.format("onServiceConnected"));
            mBluetoothService = IBluetoothService.Stub.asInterface(service);
            notifyBluetoothManagerReady();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
//            BluetoothLog.v(String.format("onServiceDisconnected"));
            mBluetoothService = null;
        }
    };

这段代码 我想问下 mBluetoothService 和 mCountDownLatch 对象会不会存在线程同步问题,应为 mConnection的回调方法和bindServiceSync不在同一个线程!mConnection的回调在主线程,这种赋值操作不在一个线程会不会有问题

@xchengDroid
Copy link
Author

BluetoothClientImpl 类里面的代码,比如mCountDownLatch 这个对象 在bindServiceSync 赋值了,没有来得及同步导致notifyBluetoothManagerReady 方法里为null

@xchengDroid
Copy link
Author

@fuhaodev

@fuhaodev
Copy link
Contributor

不会,mCountDownLatch赋值是在bindServiceSync之前,这段代码是在同一个线程的,notifyBluetoothManagerReady必然是在mCountDownLatch赋值之后回调的,是不会为空的

@fuhaodev
Copy link
Contributor

根据happens-before原则也能推到出来

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants