Java - 同步静态方法静态、方法、Java

由网友(相约奈何桥)分享简介:这是我在 this 链接."避免锁定静态方法最糟糕的解决方案是将同步"关键字放在静态方法,这意味着它将锁定该类的所有实例."The worst solution is to put the "synchronized" keywords on the staticmethods, which means it w...

这是我在 this 链接.

"避免锁定静态方法

最糟糕的解决方案是将同步"关键字放在静态方法,这意味着它将锁定该类的所有实例."

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...

阅读全文

相关推荐

最新文章