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,如果此答案解決了您的問題,請將其標記爲已接受。 –