简体   繁体   English

关于Java中的同步方法

[英]Regarding synchronized methods in Java

I have a question about synchronization of methods in Java. 我有一个关于Java中方法同步的问题。

Consider a class with 3 synchronized methods. 考虑一个具有3个synchronized方法的类。

class MyClass{

    public synchronized void methodA(){ ... }

    public synchronized void methodB(){ ... }

    public synchronized void methodC(){ ... }

}

Consider myObject , an instance of myClass . 考虑myObjectmyClass一个实例。 Which of the following is true? 以下内容哪些是对的?

Option 1: 选项1:

It's impossible for a thread to run any synchronized method in myObject , while a different thread is running any synchronized method in myObject . 线程不可能在myObject运行任何 synchronized方法,而另一个线程在myObject运行任何同步方法。

For example, while thread 1 is running methodA() of the instance myObject , thread 2 can't run any of the methods methodA() , methodB() and methodC() . 例如,虽然线程1运行methodA()的实例的myObject ,线程2不能运行的任何方法methodA() methodB()methodC()

Option 2: 选项2:

It's impossible for a thread to run a specific synchronized method in myObject , while that specific method is being run by another thread. 线程不可能在myObject运行特定的synchronized方法,而该特定方法由另一个线程运行。

For example, while thread 1 is running methodA() of the instance myObject , thread 2 can't run the method methodA() , but can run methodB() or methodC() . 例如,虽然线程1运行methodA()的实例的myObject ,线程2不能运行方法methodA()可以运行methodB()methodC() (Meaning, the three synchronized methods aren't 'connected'). (意思是,三个同步方法没有“连接”)。

第一个选项是正确的,因为基本上有一个锁用于所有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM