先看一段代码

public class Test {
    public static void main(String[] args) {
        try {
            long startTime = System.currentTimeMillis();
            int t = 100;
            CountDownLatch latch = new CountDownLatch(t);
            Num num = new Num();
            for (int i = 0; i < t; i++) {
                new Job(num, latch).start();
            }
            latch.await();
            System.out.println("目标结果:" + num.getNum());
            long endTime = System.currentTimeMillis();
            System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Num {
    private int num = 0;

    public int increment() {
        return num++;
    }

    public int getNum() {
        return num;
    }
}

class Job extends Thread {
    private Num num;
    private CountDownLatch latch;

    public Job(Num num, CountDownLatch latch) {
        this.num = num;
        this.latch = latch;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            num.increment();
        }
        latch.countDown();
    }
}

程序执行结果

目标结果:89887
程序运行时间:18ms

Num类中的increment方法并不是线程安全的,所以目标结果并不是期望的1000000。为了保证计数的准确性,我们需要在increment方法上加上关键字synchronized

class Num {
    private int num = 0;

    public synchronized int increment() {
        return num++;
    }

    public int getNum() {
        return num;
    }
}

程序执行结果

目标结果:100000
程序运行时间:34ms

目标结果与期望相同,但这是否是最好的方式呢?答案是否,我们可以使用java.util.concurrent.atomic.AtomicInteger进一步提升性能。

class Num {
    private AtomicInteger num = new AtomicInteger();;

    public int increment() {
        return num.getAndIncrement();
    }

    public int getNum() {
        return num.get();
    }
}

程序执行结果

目标结果:100000
程序运行时间:22ms

从结果看,程序运行时间大大缩减,这是何原理?

 

乐观锁和悲观锁

锁有两种:乐观锁与悲观锁。独占锁是一种悲观锁,而 synchronized 就是一种独占锁,synchronized 会导致其它所有未持有锁的线程阻塞,而等待持有锁的线程释放锁。所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。而乐观锁用到的机制就是CAS。

我们查看AtomicInteger源码得知,AtomicInteger类利用了jdk.internal.misc.Unsafe类中的weakCompareAndSetInt方法,该方法属于CAP操作(Compare and Swap),具有原子性。

 

与AtomicInteger相似的类还有:AtomicBoolean、AtomicLong、AtomicIntegerArray等。

 

posted on 2019-03-11 16:37  玄同太子  阅读(268)  评论(0编辑  收藏  举报