在Java关键部分中,我应该同步什么? [英] In Java critical sections, what should I synchronize on?

查看:132
本文介绍了在Java关键部分中,我应该同步什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,在代码中声明关键部分的惯用方法如下:

In Java, the idiomatic way to declare critical sections in the code is the following:

private void doSomething() {
  // thread-safe code
  synchronized(this) {
    // thread-unsafe code
  }
  // thread-safe code
}

几乎所有的块都在这个上同步,但是这有什么特别的原因吗?还有其他可能吗?是否有关于要同步的对象的最佳实践? (例如对象的私有实例?)

Almost all blocks synchronize on this, but is there a particular reason for this? Are there other possibilities? Are there any best practices on what object to synchronize on? (such as private instances of Object?)

推荐答案

首先,请注意以下代码片段相同。

First, note that the following code snippets are identical.

public void foo() {
    synchronized (this) {
        // do something thread-safe
    }
}

和:

public synchronized void foo() {
    // do something thread-safe
}

执行完全相同的事情。除了代码可读性和样式之外,没有偏好其中任何一个。

do exactly the same thing. No preference for either one of them except for code readability and style.

当您同步方法或代码块时,重要的是要知道为什么你正在做这样的事情,什么对象确切地锁定,用途

When you do synchronize methods or blocks of code, it's important to know why you are doing such a thing, and what object exactly you are locking, and for what purpose.

另请注意,在某些情况下,您需要客户端同步代码块,您要求的监视器(即同步对象)不一定是这个,如下例所示:

Also note that there are situations in which you will want to client-side synchronize blocks of code in which the monitor you are asking for (i.e. the synchronized object) is not necessarily this, like in this example :

Vector v = getSomeGlobalVector();
synchronized (v) {
    // some thread-safe operation on the vector
}

我建议你对并发编程有更多了解,一旦你确切知道幕后发生了什么,它将为你提供很多帮助。你应该查看 Java并行编程,这是一本关于这个主题的好书。如果您想快速浏览主题,请查看 Java Concurrency @ Sun

I suggest you get more knowledge about concurrent programming, it will serve you a great deal once you know exactly what's happening behind the scenes. You should check out Concurrent Programming in Java, a great book on the subject. If you want a quick dive-in to the subject, check out Java Concurrency @ Sun

这篇关于在Java关键部分中,我应该同步什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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