同步块锁对象问题 [英] Synchronized block lock object question

查看:134
本文介绍了同步块锁对象问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 并使用 作为锁定?

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。我通常锁定一个私有的引用,我知道没有其他代码要锁定。如果你锁定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.

这篇关于同步块锁对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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