java同步标记_为什么标记Java变量volatile会降低同步性?

所以,我刚刚学习了volatile关键字,同时写了一些例子,我将在明天的一节。我编写了一个快速的程序来演示++和--操作不是原子的。

public class Q3 {

private static int count = 0;

private static class Worker1 implements Runnable{

public void run(){

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

count++; //Inner class maintains an implicit reference to its parent

}

}

private static class Worker2 implements Runnable{

public void run(){

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

count--; //Inner class maintains an implicit reference to its parent

}

}

public static void main(String[] args) throws InterruptedException {

while(true){

Thread T1 = new Thread(new Worker1());

Thread T2 = new Thread(new Worker2());

T1.start();

T2.start();

T1.join();

T2.join();

System.out.println(count);

count = 0;

Thread.sleep(500);

}

}

}

正如预期的那样,该程序的输出大致如下:

-1521

-39

0

0

0

0

0

0

但是,当我改变时:

private static int count = 0;

private static volatile int count = 0;

我的输出更改为:

0

3077

1

-3365

-1

-2

2144

3

0

-1

1

-2

6

1

1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值