gpt4 book ai didi

java - 同一类的不同对象的同步方法

转载 作者:行者123 更新时间:2023-12-01 09:24:16 25 4
gpt4 key购买 nike

我有课c具有3个同步功能m1 , m2 , m3 。我创建了同一类的 3 个不同实例 c1 , c2 , c3每个都在不同的线程上运行 t1 , t2 , t3分别。如果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 .

关于java - 同一类的不同对象的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com