同步如何在Java中工作? [英] How Synchronization works in Java?

查看:80
本文介绍了同步如何在Java中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java同步有疑问。我想知道我的类中是否有三个Synchronized方法,并且一个线程在一个synchronized方法中获取锁定,其他两个将被锁定?我问这个问题,因为我对下面的陈述感到困惑。

I have a doubt regarding Java Synchronization . I want to know if I have three Synchronized methods in my class and a thread acquires lock in one synchronized method other two will be locked ? I am asking this question because I am confused with the following statement .


当一个线程在一个对象的同步方法中时,所有其他希望执行此同步方法或对象的任何其他同步方法的线程必须等待。此限制不适用于已具有锁定并正在执行对象的同步方法的线程。这样的方法可以调用对象的其他同步方法而不被阻止。当然,任何线程都可以随时调用对象的非同步方法

While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread


推荐答案

java中的同步是通过在某个特定对象上监视监视器来完成的。因此,如果你这样做:

Synchronization in java is done through aquiering the monitor on some specific Object. Therefore, if you do this:

class TestClass {
    SomeClass someVariable;

    public void myMethod () {
        synchronized (someVariable) {
            ...
        }
    }

    public void myOtherMethod() {
        synchronized (someVariable) {
            ...
        }
    }
}

然后这两个块将在任何时候通过执行2个不同的线程来保护,而 someVariable 不会被修改。基本上,据说这两个块与变量 someVariable 同步。

Then those two blocks will be protected by execution of 2 different threads at any time while someVariable is not modified. Basically, it's said that those two blocks are synchronized against the variable someVariable.

当你放同步对该方法,它基本上与 synchronized(this)相同,即对该方法执行该对象的同步on。

When you put synchronized on the method, it basically means the same as synchronized (this), that is, a synchronization on the object this method is executed on.

即:

public synchronized void myMethod() {
    ...
}

表示与:

Means the same as:

public void myMethod() {
    synchronized (this) {
       ...
    }
}

因此,回答你的问题 - 是的,线程将无法同时调用不同线程中的那些方法,因为它们都持有对同一监视器的引用,这个对象的监视器。

Therefore, to answer your question - yes, threads won't be able to simultaneously call those methods in different threads, as they are both holding a reference to the same monitor, the monitor of this object.

这篇关于同步如何在Java中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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