乐观锁:事情一定会发生,先上锁
悲观锁:事情未必发生,不上锁
自旋锁:是乐观锁的一种实现,
ABA问题:1.加版本(version/boolean)
CAS原子性:使用unsafe.compareAndSwap,是一条指令
排他锁:只有一个线程能访问代码
共享锁:多个线程能同时访问代码
读写锁:
读锁:读时候不允许写,能运行同时读
写锁:写的时候,不允许写也不允许读
统一锁:大粒度的锁,解决死锁
死锁的情况下,把多个锁统一成大锁
分段锁:分成小粒度的锁
ConcurrentHashMap(JDK1.7)
AtomicStampedReference:
- package com.company;
-
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.atomic.AtomicStampedReference;
-
- public class Main {
- public static void main(String[] args) throws Exception {
- AtomicStampedReference
ar = new AtomicStampedReference(new Order(0L, 0L), 0); -
- CountDownLatch cdl = new CountDownLatch(10000);
- for (int i = 0; i < 10000; i++) {
- new Thread(() -> {
- Order old;
- int stamp;
- Order o = new Order();
- do {
- old = ar.getReference();
- stamp = ar.getStamp();
- o.setSeq(old.getSeq() + 1);
- } while (!ar.compareAndSet(old, o, stamp, stamp + 1));
- cdl.countDown();
- }).start();
- }
- cdl.await();
- System.out.println(ar.getReference().getSeq());
- }
-
- static public class Order {
- private Long seq;
- private Long time;
-
- public Order() {
- }
-
- public Order(Long seq, Long time) {
- this.seq = seq;
- this.time = time;
- }
-
- public Long getSeq() {
- return seq;
- }
-
- public void setSeq(Long seq) {
- this.seq = seq;
- }
-
- public Long getTime() {
- return time;
- }
-
- public void setTime(Long time) {
- this.time = time;
- }
- }
- }