I have a class c
with 3 synchronized function m1
, m2
, m3
. I have created 3 different instances of the same class c1
, c2
, c3
each running on different threads t1
, t2
, t3
respectively. If t1
access m1
can t2
,t3
access m1
??
Asked
Active
Viewed 852 times
0

KAY_YAK
- 191
- 10
1 Answers
1
Depends. If the methods are static, then they synchronize on the class-object and interleaving is impossible. If they are non-static, then they synchronize on the this
-object and interleaving is possible. The following example should clarify the behaviour.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String... args) {
List<Thread> threads = new ArrayList<Thread>();
System.out.println("----- First Test, static method -----");
for (int i = 0; i < 4; ++i) {
threads.add(new Thread(() -> {
Main.m1();
}));
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("----- Second Test, non-static method -----");
threads.clear();
for (int i = 0; i < 4; ++i) {
threads.add(new Thread(() -> {
new Main().m2();
}));
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("----- Third Test, non-static method, same object -----");
threads.clear();
final Main m = new Main();
for (int i = 0; i < 4; ++i) {
threads.add(new Thread(() -> {
m.m2();
}));
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static synchronized void m1() {
System.out.println(Thread.currentThread() + ": starting.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + ": stopping.");
}
public synchronized void m2() {
System.out.println(Thread.currentThread() + ": starting.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + ": stopping.");
}
}
For more details, see this oracle page.

Turing85
- 18,217
- 7
- 33
- 58
-
Aaah....my bad....totally forgot static. – KAY_YAK Oct 10 '16 at 18:12
-
@KAY_YAK, if this answer solved your problem, plz mark it as accepted. – Amit Kumar Gupta Oct 11 '16 at 05:29