6.1 公平和非公平锁
6.1.1 是什么
package s02.e06;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class T1 {
volatile int n = 0;
public void add() {
n++;
}
public static void main(String[] args) {
Lock lock = new ReentrantLock();
}
}
公平锁―是指多个线程按照申请锁的顺序来获取锁,类似排队打饭,先来后到。
非公平锁是指多个线程获取锁的顺序并不是按照申请锁的顺序,有可能后中请的线程比先中请的线程优先获取锁。
在高并发的情况下,有可能会造成优先级反转或者饥饿现象。
6.1.2 两者区别
- 公平锁:Threads acquire a fair lock in the order in which they requested it
公平锁,就是很公平,在并发环境中,每个线程在获取锁时会先查看此锁维护的等待队列,如果为空,或者当前线程是等待队列的第一个,就占有锁,否则就会加入到等待队列中,以后会按照 FIFO 的规则从队列中取到自己
- 非公平锁:a nonfair lock permits barging: threads requesting a lock can jump ahead of the queue of waiting threads if the lockhappens to be available when it is requested.
非公平锁比较粗鲁,上来就直接尝试占有锁,如果尝试失败,就再采用类似公平锁那种方式。
6.1.3 题外话
Java ReentrantLock,通过构造函数指定该锁是否是公平锁,默认是非公平锁。非公平锁的优点在于吞吐量比公平锁大。
Synchronized 也是一种非公平锁
6.2 可重入锁(又名递归锁)
6.1.1 是什么
指的是同一线程外层函数获得锁之后﹐内层递归函数仍然能获取该锁的代码,在同一个线程在外层方法获取锁的时候,在进入内层方法会自动获取锁。
也即是说,线程可以进入任何一个它已经拥有的锁所同步着的代码块。
ReentrantLock/Synchronized 就是一个典型的可重入锁
可重入锁最大的作用是避免死锁
6.1.2 Synchronized
package s02.e06;
class Phone {
public synchronized void sendSMS() throws Exception {
System.out.println(Thread.currentThread().getName() + "\t invoked sendSMS()");
sendEmail();
}
public synchronized void sendEmail() throws Exception {
System.out.println(Thread.currentThread().getName() + "\t #######invoked sendEmai()");
}
}
public class ReentrantLockDemo {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(() -> {
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
}, "t1").start();
new Thread(() -> {
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
}, "t2").start();
}
}
通过上面示例我们可以看出,t1 线程在外层方法获取锁的时候,t1 在进入内层方法会自动获取锁
6.1.3 ReentrantLock
package s02.e06;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Phone implements Runnable {
Lock lock = new ReentrantLock();
@Override
public void run() {
get();
}
public void get() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "\t invoked get()");
set();
} finally {
lock.unlock();
}
}
public void set() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "\t #######invoked set()");
} finally {
lock.unlock();
}
}
}
public class ReentrantLockDemo {
public static void main(String[] args) {
Phone phone = new Phone();
Thread t3 = new Thread(phone, "t3");
Thread t4 = new Thread(phone, "t4");
t3.start();
t4.start();
}
}
package s02.e06;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Phone implements Runnable {
Lock lock = new ReentrantLock();
@Override
public void run() {
get();
}
public void get() {
lock.lock();
lock.lock(); // 多加一层锁
try {
System.out.println(Thread.currentThread().getName() + "\t invoked get()");
set();
} finally {
lock.unlock();
lock.unlock();
}
}
public void set() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "\t #######invoked set()");
} finally {
lock.unlock();
}
}
}
public class ReentrantLockDemo {
public static void main(String[] args) {
Phone phone = new Phone();
Thread t3 = new Thread(phone, "t3");
Thread t4 = new Thread(phone, "t4");
t3.start();
t4.start();
}
}
6.3 自旋锁(spinlock)
是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗 CPU
通过 CAS 操作完成自旋锁,A 线程先进来调用 myLock 方法自己持有锁 5 秒钟,B 随后进来后发现当前有线程持有锁,不是 null,所以只能通过自旋等待,直到 A 释放锁后B随后抢到。
package s02.e06;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockDemo {
// 原子引用线程
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "\t come in o(n_n)o");
while (!atomicReference.compareAndSet(null, thread)) {
}
}
public void myUnlock() {
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread, null);
System.out.println(Thread.currentThread().getName() + "\t invoked myUnLock()");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(() -> {
spinLockDemo.myLock();
// 暂停一会儿线程
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnlock();
}, "AA").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
spinLockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnlock();
}, "BB").start();
}
}
6.4 独占锁(写锁)/共享锁(读锁)/互斥锁
独占锁:指该锁一次只能被一个线程所持有。对 ReentrantLock 和 Synchronized 而言都是独占锁
共享锁:指该锁可被多个线程所持有。对 ReentrantReadWriteLock 其读锁是共享锁,其写锁是独占锁。
读锁的共享锁可保证并发读是非常高效的,读写,写读,写写的过程是互斥的。
多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取共享资源应该可以同时进行。但是如果有一个线程想去写共享资源来,就不应该再有其它线程可以对该资源进行读或写
小总结:
- 读-读能共存
- 读-写不能共存
- 写-写不能共存
- 写操作:原子 + 独占,整个过程必须是一个完整的统一体,中间不许被分割,被打断 ```java package s02.e06;
import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
// 资源类
class Mycache {
private volatile Map
// private Lock lock=new ReentrantLock();
public void put(String key, Object value) {
System.out.println(Thread.currentThread().getName() + "\t 正在写入: " + key);
// 暂停一会儿线程
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t写入完成了");
}
public void get(String key) {
System.out.println(Thread.currentThread().getName() + "\t正在读取:");
// 暂停一会儿线程
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t 读取完成:" + result);
}
}
public class ReadWriteLockDemo { public static void main(String[] args) { Mycache mycache = new Mycache();
for (int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(() -> {
mycache.put(tempInt + "", tempInt + "");
}, String.valueOf(i)).start();
}
for (int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(() -> {
mycache.get(tempInt + "");
}, String.valueOf(i)).start();
}
}
}
![image.png](https://cdn.nlark.com/yuque/0/2022/png/390086/1644732885158-8f03e825-3ff1-4aa0-b17c-4dfcdf960eb3.png#clientId=u227a32c3-c034-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=445&id=u3f2dcee6&margin=%5Bobject%20Object%5D&name=image.png&originHeight=445&originWidth=156&originalType=binary&ratio=1&rotation=0&showTitle=false&size=10806&status=done&style=none&taskId=u76d0a7f1-ddd6-403d-b1a9-347e3566e3f&title=&width=156)<br />在不加锁的情况下,写入操作被打断,完全违背了原子性
```java
package s02.e06;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
// 资源类
class Mycache {
private volatile Map<String, Object> map = new HashMap<>();
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
// private Lock lock=new ReentrantLock();
public void put(String key, Object value) {
rwLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t 正在写入: " + key);
// 暂停一会儿线程
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t写入完成了");
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.writeLock().unlock();
}
}
public void get(String key) {
rwLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t正在读取:");
// 暂停一会儿线程
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t 读取完成:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.readLock().unlock();
}
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) {
Mycache mycache = new Mycache();
for (int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(() -> {
mycache.put(tempInt + "", tempInt + "");
}, String.valueOf(i)).start();
}
for (int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(() -> {
mycache.get(tempInt + "");
}, String.valueOf(i)).start();
}
}
}
通过读写锁,保证写入操作的原子性和读取操作的高并发性