In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to understand Java inter-thread communication and waiting / notification mechanism", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to understand the communication and waiting / notification mechanism between Java threads".
Concept introduction 1. Thread communication
In the operating system, a thread is an independent individual, but in the process of thread execution, if you deal with the same business logic, it may lead to resource contention and concurrency problems. Mutexes are usually used to control the logic. But there is also a scenario where tasks are executed sequentially.
Start a data analysis task to generate report data
Report data is stored in a specified location data container
Notify the data handling task and write the data to the report library
This scenario is very common in relatively complex systems. if the process is described based on multithreading, communication and cooperation between threads is needed to deal with the scenario business methodically.
2. Waiting for notification mechanism
In the business scenario above, if thread B has been accessing the data container during the data generation process of thread A, it will result in a waste of resources to determine whether the data of the process has been generated. The normal process should be as shown in figure, thread An and thread B start at the same time, thread A begins to process the data generation task, thread B tries to obtain container data, and thread B enters the waiting state before the data is obtained. when thread A's task processing is completed, thread B is notified to get the data in the container, so as to collaborate to complete the task based on the mechanism of thread waiting and notification.
3. Basic methods
The relevant methods of the wait / notification mechanism are the basic methods at the Object level in Java, and any object has this method:
Notify: randomly notifies a thread waiting on this object to end its wait status and return
NotifyAll: wake up all waiting threads on the object and enter the object lock contention queue
Wait: the thread enters the waiting waiting state and does not scramble for lock objects. You can also set the waiting time.
The waiting notification mechanism of threads is based on these basic methods.
Second, the principle of waiting for notification 1. Basic principles
The wait / notification mechanism means that thread A calls the object wait () method to enter the waiting state without satisfying the task execution. Thread B modifies the execution condition of thread An and calls the object notify () or notifyAll () method. Thread A returns from the wait state after receiving the notification, and then performs subsequent operations. The two threads complete the interaction between waiting and notification through methods such as wait () / notify () / notifyAll () provided by the object to improve the scalability of the program.
2. Implementation case
The decoupling process of the above data generation and storage tasks is solved through thread communication.
Public class NotifyThread01 {static Object lock = new Object (); static volatile List dataList = new ArrayList (); public static void main (String [] args) throws Exception {Thread saveThread = new Thread (new SaveData (), "SaveData"); saveThread.start (); TimeUnit.SECONDS.sleep (3); Thread dataThread = new Thread (new AnalyData (), "AnalyData"); dataThread.start () } / / wait for the data to be generated, and save static class SaveData implements Runnable {@ Override public void run () {synchronized (lock) {while (dataList.size () = = 0) {try {System.out.println (Thread.currentThread (). GetName () + "wait.") Lock.wait ();} catch (InterruptedException e) {e.printStackTrace ();}} System.out.println ("SaveData." + dataList.get (0) + dataList.get (1)) } / / generate data and notify save static class AnalyData implements Runnable {@ Override public void run () {synchronized (lock) {dataList.add ("hello,"); dataList.add ("java"); lock.notify () System.out.println ("AnalyData End...");}
Note: in addition to the dataList meeting the write condition, you also need to perform a notification operation on the AnalyData thread.
Third, pipeline flow communication 1. Brief introduction of pipeline flow
Basic concept
Pipeline flow is mainly used to transfer data directly between different threads, one thread sends data to the output pipeline, and the other thread reads data from the input pipeline, thus realizing the communication between different threads.
Implement classification
Pipe byte flow: PipedInputStream and PipedOutputStream
Pipe character streams: PipedWriter and PipedReader
New IO pipeline flows: Pipe.SinkChannel and Pipe.SourceChannel
2. Use case public class NotifyThread02 {public static void main (String [] args) throws Exception {PipedInputStream pis = new PipedInputStream (); PipedOutputStream pos = new PipedOutputStream (); / / Link input stream and output stream pos.connect (pis) / / write data thread new Thread (new Runnable () {public void run () {BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); / / write data read from keyboard to pipeline stream PrintStream ps = new PrintStream (pos) While (true) {try {System.out.print (Thread.currentThread (). GetName ()); ps.println (br.readLine ()); Thread.sleep (1000) } catch (Exception e) {e.printStackTrace ();}, "input data thread:") .start () / / new Thread (new Runnable () {public void run () {BufferedReader br = new BufferedReader (new InputStreamReader (pis)); while (true) {try {System.out.println (Thread.currentThread (). GetName () + br.readLine () } catch (IOException e) {e.printStackTrace ();}, "output data thread:") .start ();}}
The writer thread writes data to the pipeline flow, and the reader thread reads the data to complete the basic communication flow.
4. Production and consumption patterns 1. Business scenarios
Thread-based waiting notification mechanism: implements the business process in which the factory produces an item and notifies the store to sell it.
2. Code implementation public class NotifyThread03 {public static void main (String [] args) {Product product = new Product (); ProductFactory productFactory = new ProductFactory (product); ProductShop productShop = new ProductShop (product); productFactory.start (); productShop.start ();}} / / Product class Product {public String name; public double price; / / whether the product is finished or not, there is no boolean flag by default } / / Product factory: production class ProductFactory extends Thread {Product product; public ProductFactory (Product product) {this.product = product;} @ Override public void run () {int I = 0 While (I < 20) {synchronized (product) {if (! product.flag) {if (I% 2 = = 0) {product.name = "mouse"; product.price = 79.99 } else {product.name = "keyboard"; product.price = 89.99;} System.out.println ("product:" + product.name+ "[price:" + product.price+ "] factory..."); product.flag = true Notify consumers of product.notifyAll ();} else {try {/ / enter waiting state product.wait () } catch (InterruptedException e) {e.printStackTrace ();} / / Product Store: sales class ProductShop extends Thread {Product product; public ProductShop (Product product) {this.product = product } @ Override public void run () {while (true) {synchronized (product) {if (product.flag = = true) {System.out.println ("Product:" + product.name+ "[price" + (product.price*2) + "] sell..."); product.flag = false Product.notifyAll (); / / Wake up the producer} else {try {product.wait ();} catch (InterruptedException e) {e.printStackTrace () }}}
Process description: ProductFactory generates an item, notifies the store to sell it, determines whether the control is in a waiting state through the flag logo, and then notifies the factory to produce the goods again after the store sells the goods.
At this point, I believe you have a deeper understanding of "how to understand the communication and waiting / notification mechanism between Java threads". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.