Java - 同步静态方法 [英] Java - synchronizing static methods

查看:27
本文介绍了Java - 同步静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 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...

这篇关于Java - 同步静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆