Analysis of lock principle in Java high concurrency 20 parallel contract (2)

Happy king, you don't know - Rui 2021-01-23 15:43:57
analysis lock principle java high


One 、 Example

  • Let's take an example park and unpark The understanding of the
package com.ruigege.LockSourceAnalysis6;

import java.util.concurrent.locks.LockSupport;

public class TestParkAndUnpark {
 public static void main(String[] args) throws InterruptedException {
  Thread thread = new Thread(new Runnable() {
   @Override
   public void run() {
    System.out.println("child thread begin park");
    // call park Method , Hang yourself
    LockSupport.park();
    System.out.println("child thread end park");
    System.out.println(" I learned another shortcut key today ,sysout + alt +/  It's the console " + 
    " A shortcut to output ");
   }
  });
  
  //  Start the child thread
  thread.start();
  Thread.sleep(1000); //  The main thread sleeps for one second , The purpose is to make the sub thread use in time
  System.out.println("main thread begin unpark");
  LockSupport.unpark(thread); //  call unpark Method , Can let the child thread thread Holding a license ,
  //  then park Method returns
 }
}
  • Let's explain the main functions of this class
  • First, a subthread is set up , And then call park Method , Because by default , The child thread does not have a license , So it hangs itself up ; Executed in the main thread unpark Method , The parameter is a child thread , The purpose of this is to enable the child thread to hold the license , Then the subthread calls park Method will return
  • Be careful :park The method doesn't tell us why we returned , Therefore, the caller needs to be invoked according to the previous park Reason for method , Check again if the conditions are met , If not satisfied , You need to call... Again park Method
  • for example : According to the comparison of interrupt status before and after calling, we can judge whether it is returned because it is interrupted .
  • Next, to illustrate calling park The thread after the method returns because it is interrupted , We modify the code
package com.ruigege.LockSourceAnalysis6;

import java.util.concurrent.locks.LockSupport;

public class TestParkAndUnpark {
 public static void main(String[] args) throws InterruptedException {
  Thread thread = new Thread(new Runnable() {
   @Override
   public void run() {
    System.out.println("child thread begin park");
    // call park Method , Hang yourself
//    LockSupport.park();
    while(!Thread.currentThread().isInterrupted()) {
     LockSupport.park();
    }
    System.out.println("child thread end park");
    System.out.println(" I learned another shortcut key today ,sysout + alt +/  It's the console " + 
    " A shortcut to output ");
   }
  });
  
  //  Start the child thread
  thread.start();
  Thread.sleep(1000); //  The main thread sleeps for one second , The purpose is to make the sub thread use in time
  System.out.println("main thread begin unpark");
//  LockSupport.unpark(thread); //  call unpark Method , Can let the child thread thread Holding a license ,
  //  then park Method returns
  
  thread.interrupt();
 }
}
20.1
20.1
  • We can see from it that , If only the child thread is interrupted , The child thread will run and end , If the child thread does not interrupt , Even if you call LockSupport(thread) Method , There will be no interruption .

Two 、void parkNanos(long nanos) Method

  • And park The method is similar to , If the thread is not licensed , So called parkNanos(long nanos) Method the thread immediately stops blocking , And back to ; If there's a license , that nanos In milliseconds , The thread will return .
  • Let's give you an example
package com.ruigege.LockSourceAnalysis6;

import java.util.concurrent.locks.LockSupport;

public class TestPark {
 public void testPark() {
  LockSupport.park();
 }
 public static void main(String[] args) {
  System.out.println(" Start park Method ");
  TestPark testPark = new TestPark();
  testPark.testPark();
 }

}
20.2
20.2
  • Here's how we use parkNanos Instead of LockSupport.park() Method
  LockSupport.park(this);
  • Use this with parameters park(Object blocker) Method , When a thread is not licensed , call park Method , It's going to get blocked up , This blocker Object will be recorded inside the thread .
  • Use jstack pid Command to view the thread stack , What objects are contained inside the thread

3、 ... and 、park(Object blocker) The source code parsing

 public static void park2(Object blocker) {
  //  Get the current thread
  Thread t = Thread.currentThread();
  // Thread One of the objects is volatile Object blocker
  //  This call setter Method , Put this blocker Recorded to the thread blocker In the object
  setBlocker(t,blocker);
  //  call park Method to block the thread
  UNSAFE.park(false,0L); // UNSAFE It's actually the thread's Unsafe Variable , We
  //  The previous definition is omitted here , Explain it directly
  setBlocker(t,null);
  //  Finally, we put blocker Object is empty , This is because the blocking has stopped
  //  This blocker Object is used to analyze the cause of thread blocking
 }
  • It's basically written after the explanation of the method

Four 、void parkNanos(Object blocker,long nanos) Method

  • In fact, there is one more time-out that can be set

5、 ... and 、void parkUtil(Object blocker,long deadline) Method

  • This method and parkNanos The difference is the timeout algorithm ,parkNanos The timeout of is calculated from the beginning of thread blocking , and parkUtil Method is timed out from 1970 From , The number of milliseconds to a point in time
 public static void parkUtile(Object blocker,long deadline) {
  Thread t = Thread.currentThread();
  setBlocker(t,blocker);
  UNSAFE.park(false,deadline);
  setBlocker(t,null);
 }

6、 ... and 、 Let's take another example

package com.ruigege.LockSourceAnalysis6;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

public class FIFOMutex {
 private final AtomicBoolean locked = new AtomicBoolean(false); //  One boolean Lock of class
 private final Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); //  A high concurrency queue
 
 public void lock() {
  boolean wasInterrupted = false//  The sign of interruption
  Thread current = Thread.currentThread();
  waiters.add(current); //  Add this thread to the queue
  // (1)
  while(waiters.peek() != current || !locked.compareAndSet(false,true)) {
   //  review compareAndSet Method , The first parameter is the expected value , The second is if is the expected value , then
   //  Set to the second parameter , Then return true
   LockeSupport.park(this);
   if(Thread.interrupted()) { // (2)
    wasInterrupted = true;
   } 
  }
  waiters.remove();
  if(wasInterrupted) { // (3)
   current.interrupt();
  }
 }
 public void unlock() {
  locked.set(false);
  LockSupport.unpark(waiters.peek());
 }
}
  • This is a first in first out lock , That is, only the first element of the queue can obtain the lock , In the code (1) If the current thread is not the team leader or the current lock has been acquired by other threads , So called park Method to hang yourself up .
  • And then the code (2) Make a judgment at the right place , If park Method is returned because it was interrupted , The interrupt is ignored , And reset the interrupt flag , Review the method to
  • In the code (3) in , Judgment marks , If it's marked true Then interrupt the thread
  • summary : In fact, other threads interrupt the thread , Although I'm not interested in interrupt signals , Ignore it ( That's code (2)), But it doesn't mean that other threads are not interested in the flag , We still need to recover .

7、 ... and 、 Source code :

版权声明
本文为[Happy king, you don't know - Rui]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210123154309258S.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云