JUC_公平锁/非公平锁/可重入锁/递归锁/自旋锁/读写锁

梦里梦外; 2023-03-12 10:50 65阅读 0赞

公平锁/非公平锁

  • 公平锁是指多个线程按照申请锁的顺序来获取锁,类似队列,先进先出
  • 非公平锁是指在多线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取到锁,在高并发的情况下,有可能造成优先级反转或者饥饿现象
  • ReentrantLock可以通过构造函数指定采用哪种方式,默认是非公平锁
  • 非公平锁的优点是吞吐量比公平锁大

可重入锁(递归锁)

同一线程外层函数获得锁之后,内层递归函数仍然能获得该锁的代码,在同一线程的外层方法获取锁的时候,在进入内层方法会自动获取锁,也就是说,线程可以进入任何一个它已经拥有的锁所同步着的代码块

synchronized

  1. public class SynchronizedDemo {
  2. public static void main(String[] args) {
  3. Phone phone=new Phone();
  4. new Thread(phone::sendEmail,"a").start();
  5. }
  6. }
  7. class Phone{
  8. public synchronized void sendMsg(){
  9. System.out.println("send message");
  10. }
  11. public synchronized void sendEmail(){
  12. System.out.println("send email");
  13. sendMsg();
  14. }
  15. }

ReentrantLock

  1. import java.util.concurrent.locks.Lock;
  2. import java.util.concurrent.locks.ReentrantLock;
  3. public class SynchronizedDemo {
  4. public static void main(String[] args) {
  5. Phone phone = new Phone();
  6. new Thread(phone::sendMsg, "a").start();
  7. }
  8. }
  9. class Phone {
  10. private Lock lock = new ReentrantLock();
  11. public void sendMsg() {
  12. lock.lock();
  13. try {
  14. System.out.println("send message");
  15. sendEmail();
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. } finally {
  19. lock.unlock();
  20. }
  21. }
  22. public void sendEmail() {
  23. lock.lock();
  24. try {
  25. System.out.println("send email");
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. } finally {
  29. lock.unlock();
  30. }
  31. }
  32. }

自旋锁

尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU

  1. import java.util.concurrent.TimeUnit;
  2. import java.util.concurrent.atomic.AtomicReference;
  3. public class SpinLockDemo {
  4. AtomicReference<Thread> atomicReference=new AtomicReference<>();
  5. public static void main(String[] args) {
  6. SpinLockDemo spinLockDemo=new SpinLockDemo();
  7. new Thread(()->{
  8. spinLockDemo.myLock();
  9. try{
  10. TimeUnit.SECONDS.sleep(3);
  11. }catch(InterruptedException e){
  12. e.printStackTrace();
  13. }
  14. spinLockDemo.myUnlock();
  15. },"a").start();
  16. try{
  17. TimeUnit.SECONDS.sleep(1);
  18. }catch(InterruptedException e){
  19. e.printStackTrace();
  20. }
  21. new Thread(()->{
  22. spinLockDemo.myLock();
  23. spinLockDemo.myUnlock();
  24. },"b").start();
  25. }
  26. public void myLock(){
  27. Thread thread=Thread.currentThread();
  28. System.out.println(thread.getName()+" come in lock");
  29. while(!atomicReference.compareAndSet(null, thread)){
  30. }
  31. }
  32. public void myUnlock(){
  33. Thread thread=Thread.currentThread();
  34. atomicReference.compareAndSet(thread, null);
  35. System.out.println(thread.getName()+" go out of lock");
  36. }
  37. }

读写锁/独占锁(写锁)/共享锁(读锁)/互斥锁(读写\写读\写写)

独占锁指该锁一次只能被一个线程所持有。ReentrantLock和synchronized都是独占锁
共享锁指该锁可以被多个线程所持有。

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.concurrent.TimeUnit;
  4. import java.util.concurrent.locks.ReadWriteLock;
  5. import java.util.concurrent.locks.ReentrantReadWriteLock;
  6. class MyCache {
  7. private volatile Map<String, Object> map = new HashMap<>();
  8. private ReadWriteLock rwLock = new ReentrantReadWriteLock();
  9. public void put(String key, Object value) {
  10. rwLock.writeLock().lock();
  11. try {
  12. System.out.println(Thread.currentThread().getName() + "\t 正在写" + key);
  13. //暂停一会儿线程
  14. try {
  15. TimeUnit.MILLISECONDS.sleep(300);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. map.put(key, value);
  20. System.out.println(Thread.currentThread().getName() + "\t 写完了" + key);
  21. System.out.println();
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. } finally {
  25. rwLock.writeLock().unlock();
  26. }
  27. }
  28. public Object get(String key) {
  29. rwLock.readLock().lock();
  30. Object result = null;
  31. try {
  32. System.out.println(Thread.currentThread().getName() + "\t 正在读" + key);
  33. try {
  34. TimeUnit.MILLISECONDS.sleep(300);
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. }
  38. result = map.get(key);
  39. System.out.println(Thread.currentThread().getName() + "\t 读完了" + result);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. } finally {
  43. rwLock.readLock().unlock();
  44. }
  45. return result;
  46. }
  47. }
  48. public class ReadWriteLockDemo {
  49. public static void main(String[] args) {
  50. MyCache myCache = new MyCache();
  51. for (int i = 1; i <= 5; i++) {
  52. final int num = i;
  53. new Thread(() -> {
  54. myCache.put(num + "", num + "");
  55. }, String.valueOf(i)).start();
  56. }
  57. for (int i = 1; i <= 5; i++) {
  58. final int num = i;
  59. new Thread(() -> {
  60. myCache.get(num + "");
  61. }, String.valueOf(i)).start();
  62. }
  63. }
  64. }

发表评论

表情:
评论列表 (有 0 条评论,65人围观)

还没有评论,来说两句吧...

相关阅读