我有一个班级c
,其中包含3个同步功能m1
,m2
,m3
。我创建了同一个类c1
,c2
,c3
的3个不同实例,每个实例分别在不同的线程t1
,t2
,t3
上运行。如果t1
访问权限m1
可以t2
,t3
访问m1
??
答案 0 :(得分:1)
取决于。如果方法是静态的,那么它们在类对象上同步并且交错是不可能的。如果它们是非静态的,那么它们在this
- 对象上同步并且可以进行交错。以下示例应阐明行为。
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.");
}
}
有关详细信息,请参阅this oracle page。