本文主要是介绍静态方法是否在高并发下造成内存混乱研究,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
先上代码
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
for (int i = 0; i < 100000; i++) {
int value = Utilty.test(1, 1);
if(value!=2){
System.out.println("t1 value=="+value);
}else{
n++;
}
}
System.out.println("t1成功次数"+n);
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
for (int i = 0; i < 100000; i++) {
int value = Utilty.test(2, 2);
if(value!=4){
System.out.println("t2 value=="+value);
}else{
n++;
}
}
System.out.println("t2成功次数"+n);
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
for (int i = 0; i < 100000; i++) {
int value = Utilty.test(3, 3);
if(value!=6){
System.out.println("t3 value=="+value);
}else{
n++;
}
}
System.out.println("t3成功次数"+n);
}
});
t1.start();
t2.start();
t3.start();
test代码:
public static int test(int a,int b){
int c = a+b;
return c;
}
调用方法结果为
test方法改为用静态变量后
static int c = 0;
public static int test(int a,int b){
c = a+b;
return c;
}
结果
结论:只要不用静态变量,静态方法在高并发下不会造成错误
这篇关于静态方法是否在高并发下造成内存混乱研究的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!