代码之家  ›  专栏  ›  技术社区  ›  bobobobo

可以吗?Synchronized(thread),那么synch块中的thread=null

  •  5
  • bobobobo  · 技术社区  · 15 年前

    我看到这个:

    // 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?
    }
    

    可以设置 thread=null 还在锁着它吗?

    我在BB码里找到了这个金块。

    5 回复  |  直到 15 年前
        1
  •  7
  •   Jon Skeet    15 年前

    是的,那很好。synchronized语句将获取它正在锁定的引用的副本,并使用该副本来计算最后要解锁的内容。

    Section 14.19 Java语言规范中的 声明表达式是在开始时求值的,并且以后不再提及它的求值。

        2
  •  3
  •   Sean Patrick Floyd    15 年前

    有一点不同:

    synchronized( this.thread )
    

    你正在同步字段上的对象 this.thread 指向

    this.thread = null;
    

    您正在重新分配字段。您没有对上面引用的对象执行任何操作,因此锁仍然有效。

        3
  •  1
  •   Michael Donohue Reno    15 年前

    同步表达式在条目时被取消引用,因此此锁的任何后续用户都将获得一个NullPointerException。您可以通过在synchronized块前面加一个空检查来解决这个问题,但随后您引入了一个race条件。

        4
  •  0
  •   irreputable    15 年前

    你可以这样做,但几乎可以肯定的是,无论代码试图实现什么,它都是错误的。发布整个代码,我保证程序员显然不理解并发性。

    不要重新分配用于同步的变量。

        5
  •  0
  •   Peter Lawrey    15 年前

    只有当您还有一个块为线程分配新值时,您才有问题。在这种情况下,有一个竞争条件,因为两个块不会锁定同一个对象,但会更新同一个字段,并且最后将值分配给哪个块是随机的。