1

I have a doubt.
Suppose in a multithreaded environment 10K users are using a site simultaniously and the site has a static method.
If a static method in JAVA creates a single instance, then the 10k-th user needs to wait for the method until rest of the users complete their usage.
Am I right?
Can anybody please explain?

4

3 回答 3

6

If a static method in JAVA create a single instance, then 10K th user need to wait for the method untill rest of the usres complete there usage.

Calling a static method doesn't create an instance implicitly. You can do so within the method, of course - but you don't have to.

Nor does creating an instance require a lock - although again, you can add synchronization should you wish to.

So in the case of a simple static method which doesn't need any synchronized access to shared data, there should be no problem with multiple threads calling that method concurrently.

于 2013-03-11T12:54:11.183 回答
2

我猜你的意思是像单身人士或工厂,例如

public class X {

    public static X getInstance() {
        return new X();
    }

    private X() {}
}

那么这一切都取决于你在静态方法上做了什么。如果该方法不关心线程(如上面的示例),那么它不应该被同步并且可以并发执行,那么你就错了,因为可以X.getInstance()并发执行并且 10Kth 不必等待之前完成。

如果该方法不能是多线程的,那么它应该是同步的(整个方法或其中的一部分),那么是的,你是对的。

于 2013-03-11T12:56:07.163 回答
0

NO..10K th 用户无需等待该方法,直到其余用户完成使用。

因为它不是静态方法不同步......所以多个线程可以访问同一个对象。

于 2013-03-11T12:55:00.827 回答