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

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

问题描述

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

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..

当你决定使用synchronized块时,你如何决定哪个对象是锁?

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上同步并将其用作锁定有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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