java - 就处理能力和内存使用而言,使用局部变量相对于实例变量有什么好处,反之亦然

标签 java

int value;
public int calculateStuff(int integer){
    value = integer + otherNumbersAndMathStuffs;

    //more math
    return mathResults
}


public int calculateStuff(int integer){
    int value = integer + otherNumbersAndMathStuffs;

    //more math
    return mathResults
}

在使用处理器能力和/或内存方面,一种方法比另一种方法更好吗?

最佳答案

前者可能会在多线程执行中产生问题,而后者则不会。

  int value;
public int calculateStuff(int integer){
    value = integer + 1;

    System.out.println(value+100);
    return mathResults
} enter code here

假设,thread-1 和 thread-2 正在同时执行,调用 带有参数 2,3 的方法。

假设,Thread-1 进入该方法并将 value 设置为 3 并yield 线程2

Thread-2进入该方法并将值设置为4并yield为 线程1

Thread-1 将打印 104

Thread-2 将打印 104

关于java - 就处理能力和内存使用而言,使用局部变量相对于实例变量有什么好处,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46481740/

相关文章:

windows - Maven 中的 Java_home

java - 无需用户名或密码即可连接到 Oracle

java - 如何在我的 CustomAdapter 上添加 OnItemClickListener

java - 使用 GWT 在 FlexTable 中进行分页

java - ThreadPoolExecutor 中的核心池大小与最大池大小

java - 所有maven模块和子模块都显示在根树列表中

java - Gradle 代理配置

java - 从 servlet 运行繁重的 cmd 进程

java - Eclipse 中运行的是什么版本的 Java?

java - 使用 Streams 同时计算总和和平方和