Java - synchronizing static methods(Java - 同步静态方法)
问题描述
这是我在 this找到的一段文字a> 链接.
"避免锁定静态方法
最糟糕的解决方案是将同步"关键字放在静态方法,这意味着它将锁定该类的所有实例."
The worst solution is to put the "synchronized" keywords on the static methods, which means it will lock on all instances of this class."
为什么同步静态方法会锁定类的所有实例?它不应该只是锁定班级吗?
Why would synchronizing a static method lock all instances of the class? Shouldn't it just lock the Class?
推荐答案
这是我的测试代码,证明你是对的,文章有点过于谨慎了:
Here's my test code that shows that you're right and the article is a bit over-cautious:
class Y {
static synchronized void staticSleep() {
System.out.println("Start static sleep");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("End static sleep");
}
synchronized void instanceSleep() {
System.out.println("Start instance sleep");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
System.out.println("End instance sleep");
}
}
public class X {
public static void main(String[] args) {
for (int i = 0; i < 2; ++i) {
new Thread(new Runnable() {
public void run() {
Y.staticSleep();
}
}).start();
}
for (int i = 0; i < 10; ++i) {
new Thread(new Runnable() {
public void run() {
new Y().instanceSleep();
}
}).start();
}
}
}
打印:
Start instance sleep
Start instance sleep
Start instance sleep
Start instance sleep
Start instance sleep
Start static sleep
Start instance sleep
Start instance sleep
Start instance sleep
Start instance sleep
Start instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End instance sleep
End static sleep
Start static sleep
End static sleep
所以 static synchronized
与实例上的 synchronized
方法无关...
So the static synchronized
has no bearing on the synchronized
methods on the instances...
当然,如果整个系统都使用静态同步
方法,那么您可以期望它们对多线程系统的吞吐量影响最大,因此请自行承担风险...
Of course if static synchronised
methods are used throughout the system, then you can expect them to have the most impact on the throughput of a multithreaded systems, so use them at your peril...
这篇关于Java - 同步静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - 同步静态方法
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01