java static 修改_Java static / non-static synchronized方法同时修改static成员变量,会有问题吗?...

Java里

static

non-static

synchronized方法锁住的分别是

对象

,因而是可以同时执行的,那么会存在修改问题吗?搜索没有得到比较关联的答案,来这里问问大家:

示例代码如下:

public class Test {

private static int staticVariableOne = 0;

public synchronized void nonStaticFunction() {

// do some works

staticVariableOne++;

// do some works

}

public synchronized static void staticFunction() {

// do some works

staticVariableOne++;

// do some works

}

}

以上,两个线程分别同时调用nonStaticFunction()和staticFunction(),会出现这种情况(导致一次修改丢失)吗:

1. nonStaticFunction 读 staticVariableOne = 0

2. nonStaticFunction 阻塞

3. staticFunction 读 staticVariableOne = 0

4. staticFunction 写 staticVariableOne = 1

5. nonStaticFunction 继续

6. staticFunction 写 staticVariableOne = 1

参考StackOverflow问题:

http://stackoverflow.com/ques…

但是,还是意犹未尽,还请各位多多指教、探讨!

补充:

运行如下测试程序,最后的结果并不是20000,中间有很多次结果都被覆盖了。

public class Test {

private static int staticVariableOne = 0;

public Test() {

super();

}

public static int getStaticVariableOne() {

return staticVariableOne;

}

public static void setStaticVariableOne(int staticVariableOne) {

Test.staticVariableOne = staticVariableOne;

}

private static void increaseStaticVariableOne() {

staticVariableOne++;

}

public synchronized void add() {

System.out.println("执行 add() 开始...");

try {

for (int i  = 0; i < 10000; i++) {

increaseStaticVariableOne();

Thread.sleep(1);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("执行 add() 完毕...");

}

public synchronized static void addStatic() {

System.out.println("执行 addStatic() 开始...");

try {

for (int i  = 0; i < 10000; i++) {

increaseStaticVariableOne();

Thread.sleep(2);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("执行 addStatic() 完毕...");

}

}

public class StudyMain {

public static void main( String[] args ) {

final Test insertData = new Test();

Thread threadOne = new Thread() {

@Override

public void run() {

insertData.add();

}

};

Thread threadTwo = new Thread() {

@Override

public void run() {

Test.addStatic();

}

};

threadOne.start();

threadTwo.start();

try {

threadOne.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

try {

threadTwo.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("After 20000 times increasements, final staticVariableOne is "

+ Test.getStaticVariableOne());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值