这是什么同步呢? [英] What's the point of this synchronization?

查看:117
本文介绍了这是什么同步呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同步点是什么位置?

为什么不直接使用 mConnectedThread.write(下)

在code段是从BluetoothChat样品为Android (这里找到)

  / **
 *写的ConnectedThread在非同步的方式
 *参数了要写入的字节
 * @see ConnectedThread#写入(字节[])
 * /
公共无效的write(byte []的输出){
    //创建临时对象
    ConnectedThreadř;
    //该ConnectedThread副本同步
    同步(本){
        如果(mState = STATE_CONNECTED!)回报;
        R = mConnectedThread;
    }
    //执行写操作不同步
    r.write(出);
}
 

解决方案

需要同步,以确保你没有不一致的状态。

如果没有同步,code将是:

 公共无效的write(byte []的输出){
    如果(mState = STATE_CONNECTED!)回报;
    mConnectedThread.write(出);
}
 

现在,如果连接在那里关闭if语句检查和方法调用之间, mConnectedThread 可能会被分配到空,方法调用执行之前。这将导致成 NullPointerException异常

What is the point of the synchronization here?

Why not just use mConnectedThread.write(out)?

The code snippet is from the BluetoothChat sample for Android (found here)

    /**
 * Write to the ConnectedThread in an unsynchronized manner
 * @param out The bytes to write
 * @see ConnectedThread#write(byte[])
 */
public void write(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
        if (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
}

解决方案

Synchronization is needed to ensure that you don't have inconsistent state.

Without the synchronization, the code would be:

public void write(byte[] out) {
    if (mState != STATE_CONNECTED) return;
    mConnectedThread.write(out);
}

Now, if the connection where to close between the if statement check and the method invocation, mConnectedThread might be assigned to null, before the method invocation execution. That would result into a NullPointerException.

这篇关于这是什么同步呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆