dingjikerbo / Android-BluetoothKit

Android BLE蓝牙通信库
Apache License 2.0
3.59k stars 738 forks source link

线程同步问题 #157

Open xchengDroid opened 3 years ago

xchengDroid commented 3 years ago
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 commented 3 years ago

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

xchengDroid commented 3 years ago

@fuhaodev

fuhaodev commented 3 years ago

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

fuhaodev commented 3 years ago

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