在 lockObject 上同步和使用 this 作为锁有什么区别? [英] What is the difference between synchronized on lockObject and using this as the lock?

查看:24
本文介绍了在 lockObject 上同步和使用 this 作为锁有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道同步方法和同步块之间的区别,但我不确定同步块部分.

I know the difference between synchronized method and synchronized block but I am not sure about the synchronized block part.

假设我有这个代码

class Test {
  private int x=0;
  private Object lockObject = new Object();

  public void incBlock() {
    synchronized(lockObject) {
      x++;
    }
    System.out.println("x="+x);
  }

  public void incThis() {  // same as synchronized method
    synchronized(this) {
      x++;
    }
    System.out.println("x="+x);
  }
}

在这种情况下,使用 lockObject 和使用 this 作为锁有什么区别?好像跟我一样..

In this case what is the difference between using lockObject and using this as the lock? It seems to be the same to me..

当您决定使用同步块时,您如何决定要锁定哪个对象?

When you decide to use synchronized block, how do you decide which object to be the lock?

推荐答案

就我个人而言,我几乎从不锁定这个".我通常锁定一个私人持有的引用,我知道没有其他代码会锁定.如果您锁定this",那么任何了解您的对象的其他代码可能会选择锁定它.虽然它不太可能发生,但它肯定会发生 - 并且可能导致死锁,或者只是过度锁定.

Personally I almost never lock on "this". I usually lock on a privately held reference which I know that no other code is going to lock on. If you lock on "this" then any other code which knows about your object might choose to lock on it. While it's unlikely to happen, it certainly could do - and could cause deadlocks, or just excessive locking.

你锁定的东西没有什么特别神奇的——你可以把它想象成一个有效的标记.使用相同令牌锁定的任何人都将尝试获取相同的锁定.除非您希望其他代码能够获得相同的锁,否则请使用私有变量.我鼓励您创建变量 final - 我不记得我曾经想要更改锁的情况在对象的整个生命周期内变量.

There's nothing particularly magical about what you lock on - you can think of it as a token, effectively. Anyone locking with the same token will be trying to acquire the same lock. Unless you want other code to be able to acquire the same lock, use a private variable. I'd also encourage you to make the variable final - I can't remember a situation where I've ever wanted to change a lock variable over the lifetime of an object.

这篇关于在 lockObject 上同步和使用 this 作为锁有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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