JUC常见的锁

一、AtomicInteger

/**
 * @author Java和算法学习:周一
 */
public class AtomicInteger {

    //不用加volatile
    public AtomicInteger count = new AtomicInteger(0);

    //不用加synchronized
    public void m() {
        for (int i = 0; i < 1000; i++) {
            //count++
            count.incrementAndGet();
        }
    }

    public static void main(String[] args) {
        T01_AtomicInteger t = new T01_AtomicInteger();

        List<Thread> threadList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            threadList.add(new Thread(t::m, "t" + i));
        }

        threadList.forEach((o)->{
            o.start();
        });

        threadList.forEach((o)->{
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(t.count);
    }

}
复制代码

1、底层实现

CAS(Compare And Swap/Set)无锁优化、乐观锁

cas(V, Expected, NewValue)

if V == E

V = New

otherwise try again or fail

V:要改的值

Expected:期望当前这个值是多少

NewValue:要设置的新值

比如要改的值是3(即最开始拿到的这个值是3),当执行CAS操作时,我期望(Expected)这个值是3,是3我才修改这个值;如果当执行CAS时,不等于我期望的值3,说明这个值被其他线程改了(假如改为了4),那我就再试一次(try again)。此时我期望这个值是4,如果执行CAS操作时,没有其他的线程再次修改这个值,即和我期望的值4相等,那我再执行CAS操作,把值修改为新值。

(1) 如果在执行CAS操作的时候,在判断值是否为我期望的值后,马上有其他线程把这个值改为了其他的值,那这种情况不是依然有问题吗?

CAS操作是CPU原语支持的,也就是说CAS的操作是CPU指令级别的操作,不允许被改变。

(2)ABA问题

(就好比 你的女朋友跟你复合时,中间又交了别的男朋友,她可能就已经变了,不再是你原来的女朋友)

就是在我执行CAS操作的时候,这个值被其他的线程修改为了2,然后又改为了3,也就是中间经过了更改。如果是基础类型,可以不用管;如果要处理,需要加版本号,也就是这个值作任何一次的修改,版本号都加1,后面检查的时候和版本号一起检查。

(3)CAS底层是怎么做到的?

里面是通过sun.misc.Unsafe类来做的(大多数方法都是native的)。该类主要作用:直接操作JVM内存(native allocateMemory)、直接生成类实例(native allocateInstance)、直接操作变量(native getInt、native getObject)、以及CAS相关操作(native compareAndSwapObject)。该类只能通过反射或者getUnsafe得到该类的对象来使用(单例),不能直接使用。

2、SyncLong VS AtomicLong VS LongAdder

/**
 * @author Java和算法学习:周一
 */
public class AtomicSynclongLongAdder {
    private static AtomicLong count1 = new AtomicLong(0L);
    private static long count2 = 0L;
    private static LongAdder count3 = new LongAdder();

    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[1000];

        //AtomicLong
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100000; j++) {
                    count1.incrementAndGet();
                }
            });
        }
        long start = System.currentTimeMillis();
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        long end = System.currentTimeMillis();
        System.out.println("AtomicLong: " + count1.get() + " time: " + (end - start));

        //long
        Object o = new Object();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100000; j++) {
                    synchronized (o) {
                        count2++;
                    }
                }
            });
        }
        start = System.currentTimeMillis();
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        end = System.currentTimeMillis();
        System.out.println("Long: " + count2 + " time: " + (end - start));

        //LongAdder
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100000; j++) {
                    count3.increment();
                }
            });
        }
        start = System.currentTimeMillis();
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        end = System.currentTimeMillis();
        System.out.println("LongAdder: " + count3.longValue() + " time: " + (end - start));
    }

}
复制代码

image.png

LongAdder内部用的是分段锁(内部也是CAS实现)。它会把值放到一个数组里,比如数组大小为4,则每一个数组里锁250个线程,每一个数组都做运算,最后再把所有的数组结果求和。所以LongAdder在超高并发时,优势特别明显。

二、ReentrantLock

1、reentrantlock可以代替synchronized,使用reentrantlock可以完成和synchronized同样的功能,但是必须得手动释放锁。使用synchronized锁定如果遇到异常,jvm会自动释放锁,但是ReentrantLock必须手动释放锁,因此经常在finally中释放锁。

2、使用reentrantlock可以进行尝试锁定(tryLock),这样无法锁定或者在指定时间内无法锁定,线程可以决定是否继续等待。

3、reentrantlock可以指定为公平锁。ReentrantLock lock=new ReentrantLock(true);表示new一个公平锁。默认是非公平锁。

1、公平锁与非公平锁

image.png

公平锁:如果一个新来的线程,首先去判断锁的等待队列有无正在等待的线程,有则进入等待队列,等前面的先运行,无则直接去抢锁,这样的锁是公平锁。先来后到

非公平锁:如果一个新来的线程,直接就去抢锁,而不去判断等待队列是否有线程在等待,这就是非公平锁。synchronized都是非公平锁

新来的线程检不检查队列是公平锁与非公平锁的关键。

2、reentrantlock VS synchronized

1、reentrantlock可以代替synchronized

2、reentrantlock必须手动关闭锁,synchronized执行结束或异常时JVM会自动释放锁

3、reentrantlock是通过CAS实现的,synchronized本质是锁升级

4、reentrantlock可以通过tryLock来进行尝试锁定

5、reentrantlock可以在公平锁与非公平锁之间切换,synchronized都是非公平锁

三、CountDownLatch(倒数 门闩)

/**
 * @author Java和算法学习:周一
 */
public class TestCountDownLatch {

    public static void usingCountDownLatch() {
        Thread[] threads = new Thread[10];
        CountDownLatch countDownLatch = new CountDownLatch(threads.length);

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                int count = 0;
                for (int j = 0; j < 10000; j++) {
                    count++;
                }
                System.out.println(count);
                countDownLatch.countDown();
            });
        }

        for (Thread thread : threads) {
            thread.start();
        }

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

        System.out.println("CountDownLatch end...");
    }

    public static void main(String[] args) {
        usingCountDownLatch();
    }

}
复制代码

countDownLatch初始大小定义为10,每增加一个线程门闩值减1(countDownLatch.countDown()), 一直等待着(countDownLatch.await()),直到门闩值为0才执行。

四、CyclicBarrier (循环 栅栏)

/**
 * @author Java和算法学习:周一
 */
public class TestCyclicBarrier {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(20, ()->{
            System.out.println("满人,发车");
        });

        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}
复制代码

CyclicBarrier大小定义为20,达到20个线程时才执行一次,否则一直等待着(barrier.await())。即以上程序会输出5次 满人,发车。

五、Phaser

/**
 * @author Java和算法学习:周一
 */
public class TestPhaser {
    private static MarriagePhaser marriagePhaser = new MarriagePhaser();

    public static void sleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class MarriagePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("所有人到齐 " + registeredParties);
                    System.out.println();
                    return false;
                case 1:
                    System.out.println("所有人吃完 " + registeredParties);
                    System.out.println();
                    return false;
                case 2:
                    System.out.println("所有人离开 " + registeredParties);
                    System.out.println();
                    return false;
                case 3:
                    System.out.println("新郎新娘抱抱 " + registeredParties);
                    return true;
                default:
                    return true;
            }
        }
    }

    static class Person implements Runnable {
        String name;

        public Person(String name) {
            this.name = name;
        }

        private void arrive() {
            sleep();
            System.out.println(name + " 到达现场");
            marriagePhaser.arriveAndAwaitAdvance();
        }

        private void eat() {
            sleep();
            System.out.println(name + " 吃");
            marriagePhaser.arriveAndAwaitAdvance();
        }

        private void leave() {
            sleep();
            System.out.println(name + " 离开");
            marriagePhaser.arriveAndAwaitAdvance();
        }

        private void hug() {
            if ("新郎".equals(name) || "新娘".equals(name)) {
                sleep();
                System.out.println(name + " 拥抱");
                marriagePhaser.arriveAndAwaitAdvance();
            } else {
                marriagePhaser.arriveAndDeregister();
            }
        }

        @Override
        public void run() {
            arrive();
            eat();
            leave();
            hug();
        }
    }

    public static void main(String[] args) {
        marriagePhaser.bulkRegister(7);

        for (int i = 0; i < 5; i++) {
            new Thread(new Person("person" + i)).start();
        }

        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();
    }

}
复制代码

image.png

类似于栅栏组,分阶段的栅栏 。所有的线程都到了某个栅栏的时候,才会执行下一步的操作。

六、ReadWriteLock

Read的时候是共享锁

Write的时候是排它锁(互斥锁)

最开始如果是读线程拿到了锁,当第二个来的线程是读线程时,可以一起读;当第二个来的是写线程时则阻塞,不允许你写,等我读完再写。

最开始如果是写线程拿到了锁,不管第二个线程是读还是写,均阻塞,必须等我改完了其他线程才能读、其他线程才能写。

/**
 * @author Java和算法学习:周一
 */
public class TestReadWriteLock {
    private static int value;

    private static ReentrantLock lock = new ReentrantLock();

    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock, int v) {
        try {
            lock.lock();
            value = v;
            Thread.sleep(1000);
            System.out.println("write..." + value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //读线程 8个
        Thread[] tRead = new Thread[8];
        for (int i = 0; i < 8; i++) {
            tRead[i] = new Thread(() -> {
                read(readLock);
            });
        }
        long start = System.currentTimeMillis();
        for (Thread t : tRead) {
            t.start();
        }
        for (Thread t : tRead) {
            t.join();
        }

        //写线程 2个
        Thread[] tWrite = new Thread[2];
        for (int i = 0; i < 2; i++) {
            tWrite[i] = new Thread(() -> {
                write(writeLock, new Random().nextInt(10));
            });
        }
        for (Thread t : tWrite) {
            t.start();
        }
        for (Thread t : tWrite) {
            t.join();
        }

        long end = System.currentTimeMillis();
        System.out.println("total time: " + (end - start));
    }

}
复制代码

如果使用Reentrantlock加锁,程序运行10s,也就是说Reentrantlock读写均是排它锁;

如果使用ReadWriteLock加锁,程序运行3s,也就是说ReadWriteLock的读是共享锁,写是排它锁。

七、Semaphore (信号灯)

初始时,给Semaphore赋默认值,该值表示最多可以允许多少个线程同时运行。即限流的意思。 Semaphore默认是非公平锁,new Semaphore(1, true) new对象时设置true即表示是公平锁。

/**
 * @author Java和算法学习:周一
 */
public class TestSemaphore {
    public static void main(String[] args) {
        Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();
                System.out.println("t1...");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("t1...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }, "t1").start();

        new Thread(()->{
            try {
                s.acquire();
                System.out.println("t2...");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("t2...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }, "t2").start();
    }

}
复制代码

八、Exchanger

image.png

/**
 * @author Java和算法学习:周一
 */
public class TestExchanger {

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> {
            String s = "T1";
            try {
                s = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + s);
        }, "t1").start();

        new Thread(() -> {
            String s = "T2";
            try {
                s = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + s);
        }, "t2").start();
    }

}
复制代码

exchange()方法是阻塞的,有一个线程调用了exchange()方法,它会一直阻塞直到第二个线程调用了exchange()方法;然后第一个线程才会往下执行。


作者:monday
链接:https://juejin.cn/post/7041892718259208199
来源:稀土掘金
 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值