公平锁:多个线程按照申请锁的顺序获取锁,类似于队列。
非公平锁:上来直接尝试占有锁,如果尝试失败,再采用类似公平锁的方式,可能会产生优先级反转或饥饿现象。优点:吞吐量比公平锁大。Synchronized也是一种非公平锁。
Lock lock = new ReentrantLock(); //默认非公平锁
可重入锁(递归锁):同一线程外层函数获得锁之后,内存递归函数仍然能获取该锁的代码。同一线程在外层方法获取锁的时候,在进入内存方法或自动获取锁。线程可以进入任何一个它已经拥有的锁所同步着的代码块。(可重入锁最大作用:避免死锁)
ReentrantLock & Synchronized是典型的可重入锁。
/**
* @author luffy
**/
public class LockDemo {
public static void main(String[] args){
Phone phone = new Phone();
new Thread(()->{
phone.sendMsg();
},"t1").start();
new Thread(()->{
phone.sendMsg();
},"t2").start();
}
}
class Phone{
public synchronized void sendMsg(){
System.out.println(Thread.currentThread().getName()+":sendMsg");
sendEmail();
}
public synchronized void sendEmail(){
System.out.println(Thread.currentThread().getName()+":sendEmail");
}
}
锁配对,加上多少锁,就要释放对应的锁。
/**
* @author luffy
**/
public class LockDemo {
public static void main(String[] args){
Phone phone = new Phone();
Thread t1 = new Thread(phone,"t1");
Thread t2 = new Thread(phone,"t2");
t1.start();
t2.start();
}
}
class Phone implements Runnable{
Lock lock = new ReentrantLock();
public void set(){
lock.lock();
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+":set");
get();
}finally {
lock.unlock();
lock.unlock();
}
}
public void get(){
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+":get");
}finally {
lock.unlock();
}
}
@Override
public void run() {
set();
}
}
自旋锁:尝试获取锁的线程不会立即阻塞,而是采用循环的方式去获取锁。优点:减少线程上下文切换的消耗;缺点:循环会消耗CPU。
自旋锁源码如下:
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
手写一个自旋锁:
/**
* @author luffy
**/
public class LockDemo {
AtomicReference atomicReference = new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"come in");
while (!atomicReference.compareAndSet(null,thread)){
}
}
public void unLock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(thread.getName()+":out");
}
public static void main(String[] args){
LockDemo demo = new LockDemo();
new Thread(()->{
demo.myLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
demo.unLock();
},"t1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
demo.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
demo.unLock();
},"t2").start();
}
}
独占锁(写锁):该锁只能被一个线程所持有(ReentrantLock和Synchronized都是独占锁)
共享锁(读锁):该锁可以被多个线程所持有。
ReentrantReadWriteLock(读写锁):
- 读-读 能共存
- 读-写 不能共存
- 写-写 不能共存
写操作:原子+独占。
/**
* @author luffy
**/
public class LockDemo {
public static void main(String[] args){
MyCache cache = new MyCache();
for(int i =0 ;i< 5;i++){
final int key = i;
new Thread(()->{
cache.put(key+"",key+"");
},String.valueOf(i)).start();
}
for(int i =0 ;i< 5;i++){
final int key = i;
new Thread(()->{
cache.get(key+"");
},String.valueOf(i)).start();
}
}
}
class MyCache{
private volatile Map map = new HashMap<>();
private ReadWriteLock lock = new ReentrantReadWriteLock();
private Lock readLock = lock.readLock();
private Lock writeLock = lock.writeLock();
public void put(String key,Object value){
writeLock.lock();
try {
System.out.println(Thread.currentThread().getName()+"开始写:"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写完毕!");
}finally {
writeLock.unlock();
}
}
public void get(String key){
readLock.lock();
try {
System.out.println(Thread.currentThread().getName()+"开始读");
Object res = map.get(key);
System.out.println(Thread.currentThread().getName()+"读完毕:"+res);
}finally {
readLock.unlock();
}
}
}