简体   繁体   English

这个可以吗? 在同步块中同步(线程),然后执行thread = null

[英]Is this ok? Synchronized( thread ), then thread=null in the synch block

I see this: 我看到了这个:

// thread is a member of this class

synchronized( this.thread )
{
  this.thread.running = false;
  this.thread.notifyAll(); // Wake up anything that was .waiting() on
  // the thread
  this.thread = null;  // kill this thread reference.
  // can you do that in a synchronized block?
}

Is it ok to set the thread=null while still keeping a lock on it? 是否可以设置thread=null同时仍保持锁定?

I found this nugget in a bit of BB code. 我在一些BB代码中找到了这个金块。

Yes, that's fine. 是的,没关系。 The synchronized statement will take a copy of the reference that it's locking on, and use the copy to work out what to unlock at the end. synchronized语句将获取其锁定的引用的副本,并使用该副本计算出最后解锁的内容。

Section 14.19 of the Java Language Specification isn't actually clear about this, but it does state that the expression is evaluated at the start - and doesn't mention evaluating it again later on. Java语言规范的第14.19节实际上并不清楚这一点,但它确实声明表达式在开始时进行了评估 - 并且未提及稍后再次对其进行评估。

There's a difference: 有区别:

synchronized( this.thread )

You are synchronizing on the Object the field this.thread points to 您正在对象上同步this.thread指向的字段

this.thread = null;

You are reassigning the field. 你正在重新分配这个领域。 You are not doing anything with the object you referenced above, so the lock is still valid. 您没有对上面引用的对象执行任何操作,因此锁定仍然有效。

The synchronized expression is dereferenced on entry, so any later users of this lock will get a NullPointerException. 同步表达式在输入时被解除引用,因此此锁的任何后续用户都将获得NullPointerException。 You can work around that by putting a null check ahead of the synchronized block, but then you've introduced a race condition. 您可以通过在同步块之前放置一个空检查来解决这个问题,但之后您已经引入了竞争条件。

You can do it, but it's almost certain that the code is wrong for whatever it is trying to achieve. 你可以做到这一点,但几乎可以肯定,代码对于它想要实现的任何东西都是错误的。 Post the entire code, and I guarantee that it is obviously the programmer doesn't understand concurrency. 发布整个代码,我保证显然程序员不懂并发。

Do not reassign a variable which is used for synchronization. 不要重新分配用于同步的变量。

You only have a problem if you also have a block which assigns a new value to thread. 如果您还有一个为线程分配新值的块,则只会出现问题。 In that case you have a race condition as the two blocks don't lock on the same object, but will update the same field and it will be random as to which block assigns the value last. 在这种情况下,您有一个竞争条件,因为两个块不会锁定同一个对象,但会更新相同的字段,并且它将随机分配最后一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM