0
我有一个类c
3同步功能m1
,m2
,m3
。我创建了分别在不同线程t1
,t2
,t3
上运行的同一类c1
,c2
,c3
的3个不同实例。如果t1
访问m1
可t2
,t3
访问m1
??同类别不同对象的同步方法
我有一个类c
3同步功能m1
,m2
,m3
。我创建了分别在不同线程t1
,t2
,t3
上运行的同一类c1
,c2
,c3
的3个不同实例。如果t1
访问m1
可t2
,t3
访问m1
??同类别不同对象的同步方法
取决于。如果方法是静态的,那么它们在类对象上同步,并且交织是不可能的。如果它们是非静态的,那么它们在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。
Aaah ....我的坏......完全忘了静态。 –
@KAY_YAK,如果此答案解决了您的问题,请将其标记为已接受。 –