Communication between threads

itread01 2021-01-21 06:46:31
communication threads


# Communication between threads JVM During execution, the memory area managed by itself will be , Divided into different data areas , It's called the runtime data area . Each thread has its own private memory space , As shown below :![ Insert picture description here ](https://img-blog.csdnimg.cn/20210120165755791.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc2MDAyMA==,size_16,color_FFFFFF,t_70#pic_center)Java Threads follow the method code in their virtual machine stack step by step , In this process, it is inevitable to use the memory area, heap or method area shared by threads . To prevent multiple threads from accessing the same memory address at the same time , Need to tell each other their status to avoid resource contention . Threads can communicate in three ways :① Share memory ② Messaging ③ Piped flow shared memory : Through reading shared memory between threads - Write to achieve implicit communication .Java The specific implementation of is :volatile Share memory . Messaging : Threads communicate with each other through explicit message transmission .Java The specific implementation of is : wait for / Notification mechanism (wait/notify),join Method . Pipe flow : Pipeline input / Output stream .## 1、 wait for / The process of notification mechanism is : Thread A For some reason , Autonomously called the object o Of wait Method , Enter WAITING Status , Release the lock in possession and wait for notification . And the thread B Then call the object o Of notify Method or notifyall Method to notify , Thread A Will receive notice , And from wait Return in method , Continue to run the following code . It can be found that , Thread A And threads B It's through objects o Of wait Methods and notify Method to send a message , Communicate .wait Methods and notify The method is Object Method of class , and Object Class is the parent of all classes , So all objects are implemented Object Method of class . That is, all objects have wait Methods and notify Method .| Method | effect | Note ||--|--|--|| wait | The thread calls the wait() Method will enter WAITING Status , Release the held object lock and wait for other threads to notify or interrupt before returning from this method .| This method can pass the number ,wait(long n): To wait for n millisecond , Enter TIME-WAITING Status , If in n No notification or interruption in milliseconds , Then return to || notify | The thread calls the notify() Method will notify a call wait Method and the thread waiting here returns . But because there may be more than one thread waiting on a shared variable , So the specific notification of which thread is random .| notifyAll() Method and notify() Methods work in the same way , But notify Is to randomly notify a thread , and notifyAll Is to notify all threads waiting on the shared variable | Due to the thread waiting / The notification mechanism needs to use shared objects , So it's calling wait Before the method , The thread must first acquire the lock for the object , That is, only in the synchronization method or block (synchronized Code block ) Call me wait Method , Calling wait After the method , Thread releases lock . The same notify Method also needs to obtain the lock of the object before calling , That is, it can only be called in synchronization method or synchronization block notify Method . If there are multiple threads waiting , Then the thread scheduler randomly selects a thread to notify . It should be noted that , The notified thread does not immediately get notification from wait Method returns , You need to wait for the lock of the object before you can get it from wait Method returns . And called notify The thread of the method does not immediately release the lock on the object when called , It's after executing the synchronization method or block (synchronized Code block ) After , To release the lock of the object . therefore , The notified thread is waiting for the call notify After releasing the lock , From wait Return in method . To sum up , wait for / The classical paradigm of notification mechanism is as follows :```java/** * Wait for the thread ( call wait Method thread ) */synchronized( Sharing objects ){ // Synchronization block , The entry condition is to get the lock while( Judging conditions ){ // To carry out wait Enter when the condition of thread task is not satisfied Sharing objects .wait() } Thread task code }/** * Notify the thread ( call notify Method thread ) */synchronized( Sharing objects ){ // Synchronization block , The entry condition is to get the lock Thread task code Change wait Conditions for thread tasks Sharing objects .notify()}``` According to the above normalization , The code is as follows :```javapublic class WaitNotify { static boolean flag = true; // Conditions that wait for the thread to continue to run down static Object lock = new Object(); // Locked objects public static void main(String[] args) throws InterruptedException { Thread waitThread = new Thread(new WaitRunnable(),"waitThread"); // With WaitRunnable Is the thread of the task class Thread notifyThread = new Thread(new NotifyRunnable(),"notifyThread"); // With NotifyRunnable Is the thread of the task class waitThread.start(); //wait Thread start Thread.sleep(2000); // Main thread sleep 2s notifyThread.start(); //notify Thread start } /** * Runnable Waiting for the implementation class * synchronized Keywords : You can modify methods or use them as synchronous blocks */ static class WaitRunnable implements Runnable{ @Override public void run() { // Yes lock Lock synchronized(lock){ // Judge , if flag For true, Then continue to wait (wait) while(flag){ try { System.out.println( Thread.currentThread().getName()+ "---flag For true, wait for @"+ new SimpleDateFormat("hh:mm:ss").format(new Date()) ); lock.wait(); // wait for , And release the lock resource } catch (InterruptedException e) { e.printStackTrace(); } } // if flag For false, Then we will work System.out.println( Thread.currentThread().getName()+ "---flag For false, Execute @"+ new SimpleDateFormat("hh:mm:ss").format(new Date()) ); } } } /** * Runnable Notification implementation class */ static class NotifyRunnable implements Runnable{ @Override public void run(){ // Yes lock Lock synchronized(lock){ // With NotifyRunnable Release... For the thread of the task class lock Lock , And after notification , With Wait Only threads of task class can jump out of loop System.out.println( Thread.currentThread().getName()+ "--- Currently holding lock , Release @"+ new SimpleDateFormat("hh:mm:ss").format(new Date()) ); lock.notifyAll(); // Notifies all threads that are waiting from wait return flag = false; try { Thread.sleep(5000); //notifyThread Thread sleep 5s } catch (InterruptedException e) { e.printStackTrace(); } } // Again lock Lock , And sleep synchronized (lock){ System.out.println( Thread.currentThread().getName()+ "--- Hold the lock again , Sleep @"+ new SimpleDateFormat("hh:mm:ss").format(new Date()) ); try { Thread.sleep(2000); // Once again let notifyThread Thread sleep 2s } catch (InterruptedException e) { e.printStackTrace(); } } } }}// This code example comes from 《Java The art of concurrent programming 》``` The results are as follows :```javawaitThread---flag For true, wait for @01:53:51notifyThread--- Currently holding lock , Release @01:53:53waitThread---flag For false, Execute @01:53:58notifyThread--- Hold the lock again , Sleep @01:53:58``` The above code is based on wait / The classic paradigm of notification , A conditional variable that sets whether a thread continues to run flag, And a shared object lock, And use synchronized Keywords are right lock Lock up .waitThread Threads are waiting threads , Try to get lock on startup , Success leads to synchronized Code block . stay synchronized In the code block , If the conditions are not met ( namely flag For true), Then waitThread The thread will enter while Turn around , And call... In the loop wait Method , Enter WAITING State and release lock resources . Until another thread calls notify Method notification from wait Method returns .notifyThread A thread is a notification thread , It will also try to get a lock on startup , Success goes into synchronized Code block . stay synchronized In the code block ,notifyThread Threads change conditions , send waitThread The thread can continue to run down ( But even flag For false), At the same time notifyThread The thread also calls notyfiAll Method , Let waitThread Thread receives notification . But pay attention to ,notifyThread Threads don't call notyfiAll Release the lock immediately after the method , It's at the end of execution synchronized The lock is released after the contents of the code block . We're in notifyThread Thread call notyfiAll After , Hibernate the thread 5s. You can see from the print results that , stay notifyThread Thread dormant 5s in , Even if waitThread The thread is notified , And the conditions for continued execution have been met (flag For flase), but waitThread The thread is here 5s It's still not being implemented . stay notifyThread Thread 5s After the end of the sleep time of , And from synchronized Block exit ,waitThread The thread continues to run . therefore , Wait for the thread to be notified , You still need to wait for the thread to release the lock , And after trying to get the lock successfully, we can really get it from wait Return in method , And continue to carry out .## 2、 Shared memory has the following code ,```java/** * @Author Feng Jian * @Date 2021/1/20 13:18 * @Version 1.0 */public class JMMTest { private static boolean run = true; public static void main(String[] args) throws InterruptedException { Thread My_Thread = new Thread(new Runnable() { @Override public void run() { while(run){ //... } } }, "My_Thread"); My_Thread.start(); // Start My_Thread Thread System.out.println(Thread.currentThread().getName()+" Sleeping @"+new SimpleDateFormat("hh:mm:ss").format(new Date())+"--"+run); Thread.sleep(1000); // Main thread sleep 1s run = false; // Change My_Thread Thread execution conditions , but My_Thread The thread doesn't stop System.out.println(Thread.currentThread().getName()+" In the process of carrying out @"+new SimpleDateFormat("hh:mm:ss").format(new Date())+"--"+run); }}``` Defines a variable run, And use it as My_Thread In thread while Conditions for loop execution . Starting My_Thread Thread , And Hibernate the main thread 1s After , Change variables run Value . The results are as follows :![ Insert picture description here ](https://img-blog.csdnimg.cn/20210120165943339.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc2MDAyMA==,size_16,color_FFFFFF,t_70#pic_center) It can be seen that , Even if it's run The value of has changed , but My_Thread The thread will not stop . Why ? This requires understanding Java The memory model of (JMM). We know ,CPU To read data from memory for calculation , But actually CPU It's not always read directly from memory . Because of CPU And memory ( It's often called main memory ) It doesn't match the speed of (CPU It's much faster than main memory ), In order to make effective use of CPU, Use multilevel cache Mechanism of , As shown in the picture ![ Insert picture description here ](https://img-blog.csdnimg.cn/20210120182634839.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc2MDAyMA==,size_16,color_FFFFFF,t_70#pic_center) therefore ,CPU The order of reading data is : register - Cache memory - Main memory . Part of the data in main memory , I'll make a copy and put it in cache in , When CPU When calculating , Will come directly from cache Read data from , After the calculation, place the calculation results in cache in , Finally, rearrange the calculation results in main memory . So each CPU Will have a copy . These are just CPU Access memory , The basic way of doing calculations . Actually , Different hardware , There will be varying degrees of differences in the interview process . such as , Different computers ,CPU There may be three levels of cache between and main memory 、 Level 4 cache 、 Level 5 cache and so on . In order to mask the memory access differences between various hardware and operating systems , Realize let Java The program can achieve consistent memory access effect under various platforms , Defined Java The memory model of (Java Memory Model,JMM).JMM The main goal of is to define access rules for variables in a program , That is, in the virtual machine, the variables are stored in the main memory and the variables are removed from the main memory . Variables are variables that can be shared by multiple threads , It includes example fields 、 Static fields and elements that make up array objects , The culture variables in the method and the arguments of the method are private to the thread , Not subject to JMM Impact of .Java The memory model of is as follows ,![ Insert picture description here ](https://img-blog.csdnimg.cn/20210120211722495.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc2MDAyMA==,size_16,color_FFFFFF,t_70#pic_center)JMM Defines the relationship between threads and main memory : Shared variables between threads are stored in main memory , Each thread has a private local memory , The local memory stores a copy of the shared variable in the main memory .JMM Regulations : Put all shared variables in main memory , When a thread uses a variable , Will copy the variables to your local memory , When a thread reads or writes, it operates on a copy of a variable in local memory . One thread cannot access the local memory of other threads . Local memory is just an abstract concept , It doesn't really exist , It contains cache 、 Write buffer 、 Registers and other hardware and compiler optimizations . In a multithreaded environment , Since each thread has a copy of the shared variable in main memory , So when the thread is running , Read a copy of the shared variable in your local memory , This raises the issue of thread security : For example, shared variables in main memory i For 1, Thread A and B Fetching variables from main memory i, Put it into your own local memory to become a shared variable i Copy of . When the thread A On execution , Will read the replica variables directly from your local memory i Value , Add 1 Calculation , Update the copy in local memory when finished i Value , Write back to main memory , At this point in main memory i The value of is 2. And if the thread B You also need variables i Value , It doesn't go to the main memory to read i Value , Instead, it reads directly from its own local memory i Copy of , And the thread B Copy in local memory of i The value of is still 1, Not through threads A Revised , The value in main memory 2. This is also why in the above code ,main The thread has obviously changed the variable run Value , but My_Thread The thread is still running while The reason for the loop . As shown in the figure ,![ Insert picture description here ](https://img-blog.csdnimg.cn/20210120224006339.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc2MDAyMA==,size_16,color_FFFFFF,t_70#pic_center) This is also JMM The problem of multithreading visibility to deal with : When a shared variable has copies in the working memory of multiple threads , If a thread changes the copy value of the shared variable , Then other threads should be able to see the modified value . That is, how to ensure that the instruction will not be affected by cpu The impact of caching . Back to the code above , How to make My_Thread The thread can receive main Thread has been modified `run = false` Information about ? namely My_Thread Threads and main How threads can communicate . According to Java The memory model of , If the two threads need to communicate , You have to go through the following two steps :>①main The thread changes the shared variable in the local memory run To the main memory .>②My_Thread Thread to the main memory to read main Shared variables that have been previously updated by the thread run Value . This means , Communication between two threads must go through main memory .Java Provide volitale Keyword to achieve this requirement .volitale Keywords can be used to modify fields ( Member variable ), inform Java Any program access to this variable is from shared memory ( Main memory ) Get from , All changes to it have to be synchronized back to shared memory , so volitale Keyword can ensure the visibility of all threads to variable access . That is, the read and write of shared variables need to go through the main memory , Therefore, the purpose of thread communication through shared memory is achieved . We know how threads communicate through shared memory , Let's rewrite the above code , send main The thread is modified `run = false` After ,My_Thread In the thread while The loop will stop immediately . In fact, you just need to give shared variables run add volitale Key words :```javaprivate static volatile boolean run = true;``` The modified execution result is as follows :![ Insert picture description here ](https://img-blog.csdnimg.cn/20210121001349329.png#pic_center) Visible , stay main Threads modify shared variables run After the value of , That is to rearrange the main memory . and My_Thread The thread reads... In main memory run The discovery value is false Then it stopped while Turn around . Actually , You can also use synchronized Keyword to ensure memory visibility , Realize thread communication . The mechanism is : stay synchronized In the modified synchronization block , If you operate on a shared variable , Will clear the value of this variable in the thread's local memory , And read the value of the shared variable in the main memory before using it . And at the end of the synchronization block , When the lock resource is released , The shared variable must be synchronized back to the main memory .## 3、 Pipe flow has not learned to use , Let's skip for a moment ...> The above is my notes in the learning process . Reference books 、 The article or blog is as follows :[1] Fang Tengfei , Wei Peng , Cheng Xiaoming . Java The art of concurrent programming [M]. Mechanical Industry Press .[2] Huo Luxu , Xue Bintian . Java The beauty of concurrent programming [M]. Electronic Industry Press .[3][Simen Lang . Please , Communication between threads is really simple . You know .https://zhuanlan.zhihu.com/p/138689342](https://zhuanlan.zhihu.com/p/138689342)[4][ King of bliss .Java Thread memory model , Thread 、 Working memory 、 Main memory . You know .https://zhuanlan.zhihu.com/p/25474331](https://zhuanlan.zhihu.com/p/2
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121064421578Q.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课程百度云