静态方法内部的变量共享 [英] Variable sharing inside static method

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

问题描述

我对静态方法中的变量有疑问. 静态方法中的变量是否共享相同的内存位置,或者它们将具有单独的内存?

I have a question about the variables inside the static method. Do the variables inside the static method share the same memory location or would they have separate memory?

这里是一个例子.

public class XYZ
{
    Public Static int A(int value)
    {
      int b = value;
      return b;
    }
}

如果3个不同的用户调用执行方法A

If 3 different user calls execute the method A

XYZ.A(10);
XYZ.A(20);
XYZ.A(30);

同时.每个调用的返回值是多少?

at the same time. What would be the return values of each call?

XYZ.A(10)=?
XYZ.A(20)=?
XYZ.A(30)=?

推荐答案

它们仍然是局部变量-它们不在线程之间共享.它们在静态方法中这一事实没有任何区别.

They're still local variables - they're not shared between threads. The fact that they're within a static method makes no difference.

如果将 static 变量用作中间变量,则不安全:

If you used a static variable as the intermediate variable, that would be unsafe:

public class XYZ
{
    // Don't do this! Horribly unsafe!
    private static int b;
    public static int A(int value)
    {
        b = value;
        return b;
    }
}

在这里,所有线程实际上都将使用相同的b变量,因此,如果您同时从多个线程中调用该方法,则线程X可以先写入b,然后再写入线程Y,这样线程X就会结束返回由线程Y设置的值.

Here, all the threads would genuinely be using the same b variable, so if you called the method from multiple threads simultaneously, thread X could write to b, followed by thread Y, so that thread X ended up returning the value set by thread Y.

这篇关于静态方法内部的变量共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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