Java基础之AtomicInteger

我们平时所用的++a并不是线程安全的,也不是原子操作,这里的++a其实包含了三个原子操作,但是对于这样的对变量直接操作怎样才能使其安全呢?这时,我们需要使用AtomicInteger。
关于AtomicInteger,自带++操作方法,之所以安全,是因为他对变量使用了volatile关键字。

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest implements Runnable {

    private AtomicInteger i = new AtomicInteger(0);

    public int getValue() {
        return i.get();
    }

    private void evenIncrement() {
        i.addAndGet(2);
    }

    @Override
    public void run() {
        while (true) {
            evenIncrement();
        }
    }

    public static void main(String[] args) {
     //定时执行任务
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.err.println("Aborting");
                System.exit(0);
            }
        }, 5000);

        ExecutorService exec = Executors.newCachedThreadPool();
        AtomicIntegerTest ait = new AtomicIntegerTest();
        exec.execute(ait);
        while (true) {
            int val = ait.getValue();
            if (val % 2 != 0) {
                System.out.println(val);
                System.exit(0);
            }
        }
    }
}

用法如上,对着写就是了,在提个问题,下面这段代码有什么区别?



    // 代码1

    public class Sample {

    private static int count = 0;

    synchronized public static void increment() {

    count++;

    }

    }


    // 代码2

    public class Sample {

    private static AtomicInteger count = new AtomicInteger(0);

    public static void increment() {

    count.getAndIncrement();

    }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值