使用synchronized、ReentrantLock与CAS自旋方式实现原子操作

示例1:线程不安全的计数器

public class AddCountDemo {

    private int i = 0;

    public static void main(String[] args) {
        final AddCountDemo synchronizDemo = new AddCountDemo();
        for (int j = 0; j < 500; j++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronizDemo.addCount();
                }
            }).start();
        }
        // 使当前所有线程运行完成之后再运行以下代码
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println(synchronizDemo.i);
    }

    private void addCount() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.i++;
    }
}

示例2:使用synchronized实现线程安全的计数器

public class AddCountSynchronizDemo {
    private int i = 0;

    public static void main(String[] args) {
        final AddCountSynchronizDemo synchronizDemo = new AddCountSynchronizDemo();
        for (int j = 0; j < 500; j++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronizDemo.addCount();
                }
            }).start();
        }
        // 使当前所有线程运行完成之后再运行以下代码
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println(synchronizDemo.i);
    }

    private void addCount() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (this) {
            this.i++;
        }
    }
}

示例3:使用ReentrantLock方式实现线程安全的计数器

import java.util.concurrent.locks.ReentrantLock;

public class AddCountReentrantDemo {
    private int i = 0;

    private ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {
        final AddCountReentrantDemo synchronizDemo = new AddCountReentrantDemo();
        for (int j = 0; j < 500; j++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronizDemo.addCount();
                }
            }).start();
        }
        // 使当前所有线程运行完成之后再运行以下代码
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println(synchronizDemo.i);
    }

    private void addCount() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        reentrantLock.lock();
        try {
            this.i++;
        } finally {
            reentrantLock.unlock();
        }
    }
}

示例4:使用CAS自旋方式实现线程安全的计数器

import java.util.concurrent.atomic.AtomicInteger;

public class AddCountCASDemo {

    private int i = 0;

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {
        final AddCountCASDemo synchronizDemo = new AddCountCASDemo();
        for (int j = 0; j < 500; j++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronizDemo.addCount();
                }
            }).start();
        }
        // 使当前所有线程运行完成之后再运行以下代码
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println(synchronizDemo.atomicInteger.get());
    }

    private void addCount() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //atomicInteger.compareAndSet()
        for (; ; ) {
            int i = atomicInteger.get();
            boolean result = atomicInteger.compareAndSet(i, ++i);
            if (result) {
                break;
            }
        }
    }
}
boolean result = atomicInteger.compareAndSet(i, ++i);
操作的时候会检查值有没有变化,如果没有发生变化则更新,而后返回true;如果操作值发生变化则返回false,程序在for循环中重新这些++i操作;
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值