Java - 同步静态方法 [英] Java - synchronizing static methods
问题描述
以下是我在此 link。
Here is a piece of text I found at this link.
避免锁定静态方法
"Avoid lock on static methods
最糟糕的解决方案是将synchronized关键字放在静态
方法上,这意味着它将锁定此类的所有实例。
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
所以静态同步
与 synchronized
方法无关在实例上......
So the static synchronized
has no bearing on the synchronized
methods on the instances...
当然如果在整个系统中使用 static synchronized
方法,那么你可以期待他们对t的影响最大多线程系统的吞吐量,所以在危险时使用它们......
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 - 同步静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!