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/