JUC_公平锁/非公平锁/可重入锁/递归锁/自旋锁/读写锁
公平锁/非公平锁
- 公平锁是指多个线程按照申请锁的顺序来获取锁,类似队列,先进先出
- 非公平锁是指在多线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取到锁,在高并发的情况下,有可能造成优先级反转或者饥饿现象
- ReentrantLock可以通过构造函数指定采用哪种方式,默认是非公平锁
- 非公平锁的优点是吞吐量比公平锁大
可重入锁(递归锁)
同一线程外层函数获得锁之后,内层递归函数仍然能获得该锁的代码,在同一线程的外层方法获取锁的时候,在进入内层方法会自动获取锁,也就是说,线程可以进入任何一个它已经拥有的锁所同步着的代码块。
synchronized
public class SynchronizedDemo {
public static void main(String[] args) {
Phone phone=new Phone();
new Thread(phone::sendEmail,"a").start();
}
}
class Phone{
public synchronized void sendMsg(){
System.out.println("send message");
}
public synchronized void sendEmail(){
System.out.println("send email");
sendMsg();
}
}
ReentrantLock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SynchronizedDemo {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(phone::sendMsg, "a").start();
}
}
class Phone {
private Lock lock = new ReentrantLock();
public void sendMsg() {
lock.lock();
try {
System.out.println("send message");
sendEmail();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void sendEmail() {
lock.lock();
try {
System.out.println("send email");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
自旋锁
尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockDemo {
AtomicReference<Thread> atomicReference=new AtomicReference<>();
public static void main(String[] args) {
SpinLockDemo spinLockDemo=new SpinLockDemo();
new Thread(()->{
spinLockDemo.myLock();
try{
TimeUnit.SECONDS.sleep(3);
}catch(InterruptedException e){
e.printStackTrace();
}
spinLockDemo.myUnlock();
},"a").start();
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.myLock();
spinLockDemo.myUnlock();
},"b").start();
}
public void myLock(){
Thread thread=Thread.currentThread();
System.out.println(thread.getName()+" come in lock");
while(!atomicReference.compareAndSet(null, thread)){
}
}
public void myUnlock(){
Thread thread=Thread.currentThread();
atomicReference.compareAndSet(thread, null);
System.out.println(thread.getName()+" go out of lock");
}
}
读写锁/独占锁(写锁)/共享锁(读锁)/互斥锁(读写\写读\写写)
独占锁指该锁一次只能被一个线程所持有。ReentrantLock和synchronized都是独占锁
共享锁指该锁可以被多个线程所持有。
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class MyCache {
private volatile Map<String, Object> map = new HashMap<>();
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
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 写完了" + key);
System.out.println();
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.writeLock().unlock();
}
}
public Object get(String key) {
rwLock.readLock().lock();
Object result = null;
try {
System.out.println(Thread.currentThread().getName() + "\t 正在读" + key);
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t 读完了" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.readLock().unlock();
}
return result;
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 1; i <= 5; i++) {
final int num = i;
new Thread(() -> {
myCache.put(num + "", num + "");
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
final int num = i;
new Thread(() -> {
myCache.get(num + "");
}, String.valueOf(i)).start();
}
}
}
还没有评论,来说两句吧...