I am learning Java concurrency right now. I came across a piece of code like this:
package pac1;
import java.util.*;
import java.util.concurrent.*;
class A1 {
public void f() {
synchronized (this) {
for (int i = 0; i < 5; i++)
System.out.println("f()");
}
}
}
class B1 {
public void g() {
synchronized (this) {
for (int i = 0; i < 5; i++)
System.out.println("g()");
}
}
}
class C1 {
public void p() {
synchronized (this) {
for (int i = 0; i < 5; i++)
System.out.println("p()");
}
}
}
public class V {
public static void main(String[] args) {
A1 a = new A1();
B1 b = new B1();
C1 c = new C1();
new Thread() {
public void run() {
a.f();
}
}.start();
new Thread() {
public void run() {
c.p();
}
}.start();
b.g();
}
}
Since this code uses different objects to call synchronized methods, I supposed that it would not prevent them from interfering with each other. However, the result is as follows:
f()
f()
f()
f()
f()
g()
g()
g()
g()
g()
p()
p()
p()
p()
p()
BTW, the result is the same using Lock:
package pac1;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class A {
Lock lock = new ReentrantLock();
public void f() {
lock.lock();
try {
for (int i = 0; i < 5; i++)
System.out.println("f()");
} finally {
lock.unlock();
}
}
}
class B {
Lock lock = new ReentrantLock();
public void g() {
lock.lock();
try {
for (int i = 0; i < 5; i++)
System.out.println("g()");
} finally {
lock.unlock();
}
}
}
class C {
Lock lock = new ReentrantLock();
public void p() {
lock.lock();
try {
for (int i = 0; i < 5; i++)
System.out.println("p()");
} finally {
lock.unlock();
}
}
}
public class Ex16 {
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
new Thread() {
public void run() {
a.f();
}
}.start();
new Thread() {
public void run() {
c.p();
}
}.start();
b.g();
}
}