Communication between threads

Program ape Owen 2021-01-21 01:12:13
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:51notifyThread--- Currently holding lock , Release @01:53:53waitThread---flag by false, function @01:53:58notifyThread--- 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 notifyThre.........

本文为[Program ape Owen]所创,转载请带上原文链接,感谢

  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课程百度云