Communication between threads

All right 222 2021-01-21 00:45:05
communication threads


Communication between threads

JVM At run time, the memory area will be managed by itself , Divided into different data areas , It's called the runtime data area . Each thread has its own private memory space , As shown in the figure below :

 Insert picture description here

Java The thread executes step by step according to the method code in its virtual machine stack , In this process, it is inevitable to use 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 .

There are three main ways of thread communication :① Shared memory ② The messaging ③ Pipe flow

Shared memory : Read shared memory between threads - Write to achieve implicit communication .Java The concrete implementation in is :volatile Shared memory .

The messaging : The communication between threads is realized by sending messages .Java The concrete implementation in is : wait for / A notification mechanism (wait/notify),join Method .

Pipe flow : Pipeline input / Output stream .

1、 wait for / A notification mechanism

The process is : Threads A For some reason , Autonomously called the object o Of wait Method , Get into WAITING state , Release the lock in possession and wait for notification . And threads B The object is called o Of notify Method or notifyall Method to notify , Threads A Will receive notice , And from wait Return in method , Continue with the rest of the code .

You can find , Threads A And thread B It's through objects o Of wait Methods and notify Method to send the message , communicate .

wait Methods and notify The method is Object Class method , and Object Class is the parent of all classes , So all the objects are implemented Object Class method . That is, all objects have wait Methods and notify Method .

Method effect remarks
wait Thread calls shared object wait() The method will then enter WAITING state , Release the occupied object lock and wait for other threads to notify or interrupt before returning from this method . This method can transfer parameters ,wait(long n): Overtime waiting n millisecond , Get into TIME-WAITING state , If in n No notification or interruption in milliseconds , Then return to
notify Thread calls shared object 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() Methods and notify() Methods work in the same way , however notify Is to randomly notify a thread , and notifyAll All threads waiting on the shared variable are notified

Because of the thread waiting / The notification mechanism needs the help of shared objects , So in calling wait Before the method , The thread must first obtain the lock on the object , That is, only in the synchronization method or block (synchronized Code block ) Call in wait Method , Calling wait After the method , Thread release lock .

alike notify Method also needs to get the lock of the object before calling , That is, it can only be invoked in synchronous or synchronous blocks notify Method . If there are multiple threads waiting , Then the thread scheduler will randomly select a thread to notify . It should be noted that , The thread that is notified does not immediately run from the wait Method returns , Instead, you need to wait for the lock of the object before you can get it from wait Method returns . And call the notify The thread of the method does not immediately release the lock of the object when it is called , It's after executing the synchronization method or block (synchronized Code block ) after , To release the lock on the object . therefore , The thread being notified is waiting to be called notify After the thread releases the lock , Get out of wait Return in method .

in summary , wait for / The classical paradigm of notification mechanism is as follows :

/**
* Wait for thread ( call wait Method thread )
*/
synchronized( Shared objects ){ // Synchronization code block , The entry condition is to get the lock
while( Judge the condition ){ // Conduct wait Enter when the condition of thread task is not satisfied
Shared objects .wait()
}
Thread task code
}
/**
* Notification thread ( call notify Method thread )
*/
synchronized( Shared objects ){ // Synchronization code block , The entry condition is to get the lock
Thread task code
change wait Conditions for thread tasks
Shared objects .notify()
}

According to the above paradigm , The code is as follows :

public class WaitNotify {
static boolean flag = true; // Wait for the thread to continue executing the condition for the next execution
static Object lock = new Object(); // The locked object
public static void main(String[] args) throws InterruptedException {
Thread waitThread = new Thread(new WaitRunnable(),"waitThread"); // With WaitRunnable Thread for task class
Thread notifyThread = new Thread(new NotifyRunnable(),"notifyThread"); // With NotifyRunnable Thread for 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 keyword : You can modify methods or use them in the form of synchronous blocks
*/
static class WaitRunnable implements Runnable{
@Override
public void run() {
// Yes lock Lock
synchronized(lock){
// Judge , if flag by true, Then continue to wait (wait)
while(flag){
try {
System.out.println(
Thread.currentThread().getName()+
"---flag by 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 by false, Then we will work
System.out.println(
Thread.currentThread().getName()+
"---flag by false, function @"+
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 The thread of task class can jump out of the loop
System.out.println(
Thread.currentThread().getName()+
"--- Currently holding lock , Release @"+
new SimpleDateFormat("hh:mm:ss").format(new Date())
);
lock.notifyAll(); // Notify all waiting threads from wait return
flag = false;
try {
Thread.sleep(5000); //notifyThread Thread to 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); // Let... Again notifyThread Thread to sleep 2s
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
// This code example comes from 《Java The art of concurrent programming 》

The result is as follows :

waitThread---flag by true, wait for @01:53:51
notifyThread--- Currently holding lock , Release @01:53:53
waitThread---flag by false, function @01:53:58
notifyThread--- Hold the lock again , Sleep @01:53:58

The above code is based on wait / The classic paradigm of notification , Set a condition variable for the thread to continue to execute flag, And a shared object lock, And use synchronized Key words to lock locked .

waitThread A thread is a waiting thread , Try to get lock on startup , Success leads to synchronized Code block . stay synchronized Block of code , If the conditions are not met ( namely flag by true), be waitThread The thread will enter while loop , And it is called in the loop body wait Method , Get into WAITING State and release lock resources . Until other threads call 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 Block of code ,notifyThread Threads change conditions , send waitThread The thread can continue to execute ( But even flag by false), meanwhile notifyThread The thread also calls the notyfiAll Method , Give Way 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 are notifyThread Thread calls notyfiAll after , Hibernate the thread 5s. It can be found from the print results that , stay notifyThread Thread dormant 5s in , Even if waitThread The thread is notified , And the conditions for continuous operation have been met (flag by flase), but waitThread The thread is here 5s It's still not being implemented . stay notifyThread Threads 5s After the end of the sleep time of , And from synchronized Code block exit ,waitThread The thread continues to execute . therefore , Wait for the thread to be notified , You still need to wait for the notification 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 .

2、 Shared memory

There are the following codes ,


/**
* @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-up My_Thread Threads
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 running conditions , but My_Thread Threads don't stop
System.out.println(Thread.currentThread().getName()+" Running @"+new SimpleDateFormat("hh:mm:ss").format(new Date())+"--"+run);
}
}

Defines a variable run, And take it as My_Thread In the thread while The conditions for loop execution . Start up My_Thread Threads , And Hibernate the main thread 1s after , Change variables run Value . The result is as follows :

 Insert picture description here

It can be seen that , Even if it's run The value of has changed , but My_Thread Threads still don't stop . Why? ? This requires understanding Java Memory model (JMM).

We know ,CPU To read data from memory for calculation , But actually CPU It's not always read directly from memory . because 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 multistage cache The mechanism of , Pictured

 Insert picture description here

therefore ,CPU The order of reading data is : register - Cache - Main memory . Part of the data in main memory , I'll make a copy and put it in cache in , When CPU When calculating , Directly from cache Read data from , After the calculation, place the calculation results in cache in , Finally, refresh the result in main memory . So every 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 memory and main memory 、 Level 4 cache 、 Five level cache and so on .

In order to shield the memory access differences of various hardware and operating systems , Let's realize Java The program can achieve consistent memory access effect under various platforms , Defined Java Memory model (Java Memory Model,JMM).

JMM The main goal is to define the access rules of each variable in the program , That is to say, the underlying details of storing variables in main memory and fetching variables from main memory in virtual machine . Variables here refer to variables that can be shared by multiple threads , It includes instance fields 、 Static fields and the elements that make up the array object , The local variables in the method and the parameters of the method are private to the thread , Not subject to JMM Influence .

Java The memory model of is as follows ,

 Insert picture description here
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 , Local memory stores copies of shared variables in main memory .

JMM Regulations : Put all shared variables in main memory , When a thread uses variables , It will copy the variables to its own local memory , When a thread reads and 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 the cache 、 Write buffer 、 Registers and other hardware and compiler optimizations .

In multithreaded environment , Because 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 leads to thread security issues : Like shared variables in main memory i by 1, Threads A and B Fetching variables from main memory i, Put it into your local memory and become a shared variable i Copy of . When a thread A Execution time , 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 , In main memory at this time i The value of is 2.

And if the thread B You also need variables i Value , It doesn't go to main memory to read i Value , Instead, it reads directly from its own local memory i Copy of , And at this point the thread B Local memory copy of i The value of is still 1, Instead of going through threads A The modified , The value in main memory 2.

That's why in the above code ,main The thread has obviously modified the variable run Value , but My_Thread The thread is still executing while Reasons for the cycle . As shown in the figure ,

 Insert picture description here

It's the same thing 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 modifies 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 Memory model , If the two threads need to communicate , You have to go through the following two steps :

①main Thread changes the shared variable in local memory run Refresh the value of to main memory .
②My_Thread Thread to main memory to read main Shared variables that have been previously updated by the thread run Value .

It 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 variables ), inform Java Any program access to this variable is from shared memory ( Main memory ) In order to get , Changes to it must be synchronized back to shared memory , so volitale Keyword can ensure the visibility of all threads to variable access . That is, reading and writing shared variables need to go through the main memory , Therefore, the purpose of thread communication through shared memory is achieved .

Know how threads communicate through shared memory , Let's rewrite the above code , send main Thread modification finished run = false after ,My_Thread In thread while The cycle stops immediately .

In fact, you just need to give shared variables run add volitale Key words can be used :

private static volatile boolean run = true;

The modified results are as follows :

 Insert picture description here
so , stay main Threads modify shared variables run After the value of , Refresh back to main memory . and My_Thread Thread reads... In main memory run The discovery value is false Then it stopped while loop .

actually , You can also use synchronized Keyword to ensure memory visibility , Implement 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 this variable in main memory again before using this shared variable . And at the end of the synchronization block , When the lock resource is released , The shared variable must be synchronized back to main memory first .

3、 Pipe flow

Because I haven't learned how to use , Let's skip it for a while ...

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 Lu continued , 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
[4] King of bliss .Java Thread memory model , Threads 、 The working memory 、 Main memory . You know .https://zhuanlan.zhihu.com/p/25474331

版权声明
本文为[All right 222]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121004451594d.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课程百度云