简体   繁体   English

Java中同步时的方法可访问性

[英]methods accessibility while synchronization in java

Suppose there are four methods(m1, m2, m3, m4) and two threads(t1, t2) , now I want to know below- 假设有四个方法(m1,m2,m3,m4)两个线程(t1,t2) ,现在我想知道以下内容:

1. Non-static case: 1.非静态情况:

a) Suppose all methods are synchronized but non-static and say t1 is accessing m1, then can t2 access m2/m3/m4 ? a)假设所有方法都是同步但非静态的,并且说t1正在访问m1,那么t2可以访问m2 / m3 / m4吗?

b) Suppose m1 & m2 are synchronized and m3 & m4 are non-synchronized , all are non-static , now say t1 is accessing m1, then can t2 access m2/m3/m4 ? b)假设m1和m2是同步的,m3和m4是非同步的都是非静态的 ,现在说t1正在访问m1,那么t2可以访问m2 / m3 / m4吗?

2. Static case: 2.静态情况:

a) Suppose all methods are synchronized & static and say t1 is accessing m1, then can t2 access m2/m3/m4 ? a)假设所有方法都是同步且静态的,并且假设t1正在访问m1,那么t2可以访问m2 / m3 / m4吗?

b) Suppose all methods are static and m1 & m2 are synchronized and m3 & m4 are non-synchronized , now say t1 is accessing m1, then can t2 access m2/m3/m4 ? b)假设所有方法都是静态的,并且m1和m2是同步的,m3和m4是非同步的 ,那么假设t1正在访问m1,那么t2可以访问m2 / m3 / m4吗?

3. Mixed Case: 3.混合大小写:

a) m1&m2- static & synchronized , m3&m4- non-static & non-synchronized . a) m1&m2-静态和同步m3&m4-非静态和非同步 Now say t1 is accessing m1, then can t2 access m2/m3/m4 ? 现在说t1正在访问m1,那么t2可以访问m2 / m3 / m4吗?

b) m1- static & synchronized , m2- static & non-synchronized , m3- non-static & synchronized , m4- non-static & non-synchronized . B)M1-静态&同步 ,M2-静态&非同步 ,M3-非静态&同步 ,M4-非静态&非同步 Now say t1 is accessing m1, then can t2 access m2/m3/m4 ? 现在说t1正在访问m1,那么t2可以访问m2 / m3 / m4吗?

Can someone please answer and explain on above ? 有人可以在上面回答并解释吗? Thanks ! 谢谢 !

1. 1。
a) No. a)不
b) Only m3 and m4 . b)仅m3m4
2. 2。
a) No. a)不
b) Only m3 and m4 . b)仅m3m4
3. 3。
a) Only m3 and m4 . a)仅m3m4
b) Yes. b)是的。

According to the JLS : 根据JLS

A synchronized statement acquires a mutual-exclusion lock on behalf of the executing thread, executes a block, then releases the lock. 同步语句代表执行线程获取互斥锁,执行一个块,然后释放该锁。 While the executing thread owns the lock, no other thread may acquire the lock. 当执行线程拥有该锁时,其他任何线程都无法获取该锁。

In the case of a synchronized non static method the lock is acquired on the monitor associated with the instance the method was invoked on. 对于同步非静态方法,将在与调用该方法的实例相关联的监视器上获取锁。

In the case of a synchronized static method the lock is acquired on the monitor associated with the Class object of the class in which the called method is defined. 对于同步静态方法,将在与定义了被调用方法的类的Class对象关联的监视器上获取锁。

See the Synchronization section in the JLS. 请参阅JLS中的“ 同步”部分。

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

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