为什么80%的码农都做不了架构师?>>>
ReentrantLock重入锁简单理解就是对同一个线程而言,它可以重复的获取锁。例如这个线程可以连续获取两次锁,但是释放锁的次数也一定要是两次
Lock lock=new ReentrantLock(true);//公平锁
Lock lock=new ReentrantLock(false);//非公平锁
公平锁指的是线程获取锁的顺序是按照加锁顺序来的,而非公平锁指的是抢锁机制,先lock的线程不一定先获得锁。Java的synchronized关键字就是非公平锁
package com.example.web.controller;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock;@RestController public class ThreadController {//测试每次请求是否重新初始化int single = 0;private ReentrantLock lock = new ReentrantLock();private ReentrantReadWriteLock lockRW = new ReentrantReadWriteLock();//设置程序进入等待状态private Condition condition = lock.newCondition();@RequestMapping("thread")public int test() {//练习锁机制,开启几个线程for (int i = 0; i < 5; i++) {new Thread(() -> {try {lock.lock();//此处测试线程等待和线程唤醒System.out.println("线程进入等待状态");condition.await();thread();} catch (Exception ex) {} finally {lock.unlock();}}).start();}single++;System.out.println(single);return single;}//写一个方法用来唤醒线程@RequestMapping("/thread/signal")public void signal() {lock.lock();condition.signal();lock.unlock();System.out.println("线程已被唤醒");}//写一个方法用来多线程调用public void thread() throws Exception {//写个循环用来多线程干扰for (int i = 0; i < 5; i++) {System.out.println("线程" + i + ":" + Thread.currentThread().getName());//得稍微耗时一下才行Thread.sleep(50);}}}
private ReentrantReadWriteLock lockRW = new ReentrantReadWriteLock();//读写锁
Lock类有读锁和写锁,读读共享,写写互斥,读写互斥
参考链接:https://www.cnblogs.com/-new/p/7256297.html
java原子类使用的就是原子锁,核心方法就是compareAndSet,也就是常说的CAS,用来对比更新,写一段伪代码,current会和实际值对比,如果相同则更新成next值,否则继续循环。
public final int incrementAndGet() {for (; ; ) {//获取当前值int current = get();//设置期望值int next = current + 1;//调用Native方法compareAndSet,执行CAS操作if (compareAndSet(current, next))//成功后才会返回期望值,否则无线循环return next;} }
讲解自旋锁等相关知识:
https://blog.csdn.net/qq_34337272/article/details/81252853
https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247484911&idx=1&sn=1d53616437f50b353e33edad6fda2e4f&source=41#wechat_redirect
各种锁介绍:https://www.cnblogs.com/lzh-blogs/p/7477157.html