volatile AtomicInteger java多线程操作 原子性

volatile关键字要求线程在使用变量的时候,必须马上从主内存读取,在修改完成之后,马上将数据写入主内存。
这个过程无法对线程进行同步。
比如:
线程1从主内存读取到count的值为2,还没有操作的时候,线程2从主内存也把count读取到线程内部,这个时候依然是2.
然后线程1把count自加1设为3,立即刷新到主内存里面。线程2也把counter自加1设置为3,刷新到主内存里面
这样,线程2的操作就丢失了。

因此可以使用加锁或者AtomicInteger关键字来处理


public class VolatileWrong {


volatile static int count  = 0;

public static void main(String[] args) {

new VolatileWrong().new ThreadHandler().start();
new VolatileWrong().new ThreadHandler().start();
new VolatileWrong().new ThreadHandler().start();
new VolatileWrong().new ThreadHandler().start();

try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}


class ThreadHandler extends Thread {
@Override
public void run() {
for(int i = 0; i< 10000; i++){
count++;
}
}
}
}


===============================================

import java.util.concurrent.CountDownLatch;


public class VolatileWrong1 {


volatile static int count  = 0;

public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(4);

new VolatileWrong1().new ThreadHandler(cdl).start();
new VolatileWrong1().new ThreadHandler(cdl).start();
new VolatileWrong1().new ThreadHandler(cdl).start();
new VolatileWrong1().new ThreadHandler(cdl).start();

try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(count);
}


class ThreadHandler extends Thread {
CountDownLatch cdl ;

ThreadHandler(CountDownLatch cdl){
this.cdl = cdl;
}

@Override
public void run() {
for(int i = 0; i< 1000000; i++){
count++;
}
cdl.countDown();
}
}
}


==============应使用如下代码==========================


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;


public class VolatileWrong2 {


static AtomicInteger count = new AtomicInteger(0) ;

public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(4);

new VolatileWrong2().new ThreadHandler(cdl).start();
new VolatileWrong2().new ThreadHandler(cdl).start();
new VolatileWrong2().new ThreadHandler(cdl).start();
new VolatileWrong2().new ThreadHandler(cdl).start();

try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(count);
}


class ThreadHandler extends Thread {
CountDownLatch cdl ;

ThreadHandler(CountDownLatch cdl){
this.cdl = cdl;
}

@Override
public void run() {
for(int i = 0; i< 1000000; i++){
count.incrementAndGet();
//count.getAndIncrement();
}
cdl.countDown();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值