Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use wait and notify in Java to realize the communication between threads

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

The knowledge of this article "how to use wait and notify in Java to achieve communication between threads" is not understood by most people, so the editor summarizes the following, detailed contents, clear steps, and a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use wait and notify to achieve communication between threads in Java".

one。 Why thread communication is needed

Threads are concurrent and parallel execution, which shows that threads execute randomly, but in practical application, we have requirements on the execution order of threads, which requires thread communication.

Why not use priority to resolve the running order of threads in thread communication?

The total priority is determined by the priority information in the thread pcb and the thread wait time, so the general development does not rely on the priority to represent the execution order of the thread.

Look at the following scenario: an example of a bakery to describe the producer-consumer model

There is a bakery with bakers and customers, corresponding to our producers and consumers, while the bakery has a stock for storing bread, which is no longer produced when the stock is full, and consumers are also buying bread. when the bread in stock is sold out, consumers must wait for new bread to be produced before they can continue to buy.

Analysis: when to stop production and when to stop consumption need to be applied to thread communication to accurately convey production and consumption information

two。 Wait and notify methods

Wait (): let the object lock held by the current thread be released and wait

Wait (long timeout): the corresponding parameter is the time the thread waits

Notify (): wake up the thread that uses the same object to call wait to enter the waiting thread and re-compete for the object lock

NotifyAll (): if there are multiple threads waiting, notifyAll wakes up all, and notify wakes up one at random

Note:

These methods belong to the methods in the Object class.

Must be used in the synchronized synchronization code block / synchronization method

Which object is locked, which object wait,notify is used.

Do not wake up immediately after calling notify, but wait until the end of synchronized.

1. Wait () method

After calling the wait method:

Causes the thread executing the current code to wait (the thread is placed in the waiting queue)

Release the current lock

Wake up when certain conditions are met and retry to acquire the lock

The condition under which wait waits for completion:

Other threads call the object's notify method

Wait wait time timed out (timeout parameter to specify wait time)

Other threads call the interrupted method, causing wait to throw an InterruptedException exception

2. Notify () method

When using the wait method with no parameters, the notify method is required to wake up the thread to wait

This method is to wake up threads waiting for the object lock of the object so that they can reacquire the object lock of the object.

If there are multiple threads waiting, a thread in wait state is randomly selected by the thread scheduler (there is no first-come-first-arrive thread).

After the notify () method, the current thread will not release the object lock immediately, but will not release the object lock until the thread executing the notify () method finishes executing the program, that is, after exiting the synchronous code block.

3. NotifyAll () method

This method has the same effect as the notify () method, except that when it wakes up, it wakes up all waiting threads.

The notify () method simply wakes up a thread at random

three。 Using wait and notify to realize bakery business

Premise statement:

There are two bakers, who can make two loaves of bread at a time.

The warehouse can store 100 pieces of bread

There are 10 consumers, each buying one bread at a time

Note:

Consumption and production are carried out in parallel at the same time, not one production at a time.

Implementation code:

Public class Bakery {private static int total;// inventory public static void main (String [] args) {Producer producer = new Producer (); for (int I = 0 I)

< 2;i++){ new Thread(producer,"面包师傅-"+(i-1)).start(); } Consumer consumer = new Consumer(); for(int i = 0;i < 10;i++){ new Thread(consumer,"消费者-"+(i-1)).start(); } } private static class Producer implements Runnable{ private int num = 3; //生产者每次生产三个面包 @Override public void run() { try { while(true){ //一直生产 synchronized (Bakery.class){ while((total+num)>

100) {/ / the warehouse is full, the producer is waiting for Bakery.class.wait ();} / waiting for release total + = num; System.out.println (Thread.currentThread (). GetName () + "production bread, inventory:" + total) Thread.sleep; Bakery.class.notifyAll (); / / Wake up production} Thread.sleep (500);} catch (InterruptedException e) {e.printStackTrace () } private static class Consumer implements Runnable {private int num = 1; / / consumers consume one piece of bread at a time @ Override public void run () {try {while (true) {/ / always consume synchronized (Bakery.class) {while ((total-num))

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report