[英]Java synchoronize on copy of object rather then the actual object
I am looking at the bluetooth chat example and I don't understand why in the code bellow it is syncronzed on a copy of the local ConnectedThread object. 我正在看蓝牙聊天示例,但我不明白为什么在下面的代码中将它同步到本地ConnectedThread对象的副本上。 Surely r & mConnectedThread point to the same object?
r&mConnectedThread确定指向同一对象吗?
public synchronized void write(byte[] out)
{
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this)
{
if (mState != ICommsService.STATE_CONNECTED)
return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
It's not synchronized on the ConnectedThread object. 这不是ConnectedThread对象上同步。 It's synchronized on
this
, so that no other thread can modify mState
and mConnectedThread
when the current thread needs them. 它同步于
this
,所以没有其他线程可以修改mState
和mConnectedThread
在当前线程需要他们。
The comment who is probably confusing you says that's it's synchronizing a copy of the ConnectedThread
(that is, it makes the copy of the reference to the ConnectedThread
and that the copy process is synchronized). 可能使您感到困惑的评论说,这是因为它正在同步
ConnectedThread
的副本(也就是说,它使对ConnectedThread
的引用的副本复制,并且复制过程已同步)。 The comment does not say that it is synchronizing on the copy of the ConnectedThread
. 注释不说,它是在副本同步
ConnectedThread
。
And the reason why the function puts the reference to the ConnectedThread object in a local variable r
before using it is to be able to not synchronize the whole object when calling write
, which can be a long action. 该函数之所以在使用它之前将对ConnectedThread对象的引用放在局部变量
r
中的原因是,在调用write
时可能不同步整个对象,这可能是一个漫长的动作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.