search
HomeJavajavaTutorialHow to use wait() and notify() methods in Java to operate instances of shared resources

This article mainly introduces in detail how Java uses the wait() notify() method to operate shared resources. It has a certain reference value. Interested friends can refer to

Java Multiple Threads Shared resources;

 1) The wait(), notify() and notifyAll() methods are local methods and are final methods and cannot be overridden.

 2) Calling the wait() method of an object can block the current thread, and the current thread must own the monitor (i.e. lock, or monitor) of this object

 3) Call The notify() method of an object can wake up a thread that is waiting for the monitor of this object. If there are multiple threads waiting for the monitor of this object, only one of them can be woken up;

 4) Call The notifyAll() method can wake up all threads that are waiting for the monitor of this object;

In Java, there are no methods similar to PV operations, process mutual exclusion, etc. JAVA's process synchronization is achieved through synchronized(). It should be noted that Java's synchronized() method is similar to the mutually exclusive memory block in the operating system concept. In the Object class object in Java, there is a For memory locks, after a thread acquires the memory lock, other threads cannot access the memory, thereby realizing simple synchronization and mutual exclusion operations in Java. If you understand this principle, you can understand the difference between synchronized(this) and synchronized(static Mutually exclusive operation, and static members are exclusive to the class, and their memory space is shared by all members of the class. This causes synchronized() to lock the static members, which is equivalent to locking the class, that is, between all members of the class. To implement mutual exclusion, only one thread can access instances of this class at the same time. If you need to wake up each other between threads, you need to use the wait() method and nofity() method of the Object class.

After talking so much, you may not understand it, so let’s use an example to illustrate the problem. Use multi-threading to achieve continuous 1,2,1,2,1,2,1,2, 1,2 output.


package com.study.thread;
/**
 * 多线程
 * @ClassName: PrintFile 
 * @date 2017年10月10日 下午4:05:04
 */
public class PrintFile implements Runnable{
  //当前线程id
  private int id ;
  //共享资源
  public byte[] res ;
  
  //如果类里写了有参构造器,而任然想保留无参数构造方法,则必须显式的写出该方法。
  public PrintFile() {
    super();
//    System.out.println("我是构造器"); 
  }

  public PrintFile(int id, byte[] res) {
    //构造器中使用super()/this(),必须放在第一行。
    this(); 
    this.id = id;
    this.res = res;
  }

  //静态计数器
  public static int count = 5;
  
  @Override
  public void run() {
    synchronized (res) {
      while(count-->=0){
        try {
          res.notify();//唤醒其他线程中的某一个(唤醒等待res的其他线程,当前线程执行完后要释放锁)
          System.out.println("当前线程id值:"+id);
          
          res.wait();//当前线程阻塞,等待被唤醒
          System.out.println("现在执行的线程是"+Thread.currentThread().getName()+",--wait()后的代码继续执行:"+id);
          
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      return; 
    }
  }
}

Test:


package com.study.thread;

public class PrintFileTest {
 public static void main(String[] args) {
  byte[] res = new byte[]{0,1,2};//共享资源
  PrintFile p1 = new PrintFile(1, res);
  PrintFile p2 = new PrintFile(2, res);
  
  Thread t1 = new Thread(p1, "a");
  Thread t2 = new Thread(p2, "b");
    
  t1.start();
  t2.start();
 }
}

Result:

Current thread id value: 1
Current thread id value: 2
The thread currently executed is a,--the code after wait() continues to execute: 1
Current thread id value: 1
The thread currently executed is b,-- The code after wait() continues to execute: 2
Current thread id value: 2
The thread currently executed is a, --the code after wait() continues to execute: 1
Current thread id value: 1
The thread currently executed is b, the code after --wait() continues to execute: 2
Current thread id value: 2
The thread currently executed is a, the code after --wait() continues Execution: 1

The following explains why such a result occurs:

First, threads 1 and 2 are started. It is assumed that thread 1 runs the run method first to obtain resources (actually it is uncertain ), obtain the lock of object a, and enter the while loop (used to control several rounds of output):

1. At this time, the object calls its wake-up method notify(), which means that after the synchronization block is executed, it will Release the lock and hand the lock to the thread waiting for a resource;

2. Output 1;

3. The object executes the waiting method, which means the thread that owns the object lock from this moment on (That is, thread No. 1 here) releases CPU control, releases the lock, and the thread enters the blocking state. The following code is not executed temporarily because the synchronization block has not been executed, so 1 has no effect;

4. At some point before this, thread 2 ran the run method, but it was unable to continue running because it did not obtain the lock of object a. However, after step 3, it obtained the lock of object a, and at this time, it executed the wake-up method notify() of a. ,Similarly, it means that after the execution of this synchronization block, it will release the lock and hand the lock to the thread waiting for resource a;

5. Output 2;

6.Execute waiting for a method, which means that the thread that owns the object lock from this moment (that is, thread No. 2 here) releases CPU control, releases the lock, and the thread enters the blocking state. The subsequent code will not be executed temporarily because the synchronization block has not been executed. , so the 4-step wake-up method of thread No. 2 does not work;

7. At this time, thread No. 1 executes step 3 and finds that the object lock is not used, so it continues to execute the wait method in step 3. code, so the output is: ------Thread 1 acquires the lock, and the code after wait() continues to run: 1;

8. At this time, the while loop meets the conditions and continues to execute, so execute again The wake-up method of thread No. 1 means that it will release the lock after the synchronization block is executed;

9, output 1;

10, execute the wait method, thread 1 blocks, and releases the resource lock ;

11. At this time, Thread 2 has obtained the lock again. It proceeds to step 6 and continues to execute the code after the wait method, so the output is: ------Thread 2 obtains the lock, after wait() The code continues to run: 2;

12. Continue to execute the while loop and output 2;

··· ···

Through the above steps, I believe everyone has understood these two This method is used, but there is still a problem in the program. When the while loop does not meet the conditions, there must be threads still waiting for resources, so the main thread will never terminate. Of course, the purpose of this program is just to demonstrate how to use these two methods.

Summarize:

The wait() method and notify() must be used together with synchronized(resource). That is to say, wait and notify operate on the thread that has acquired the resource lock. From a syntax perspective, Obj.wait() and Obj.notify must be within the synchronized(Obj){...} statement block. Functionally speaking, after acquiring the object lock, the wait() thread actively releases the CPU control and the object lock, and at the same time, this thread sleeps. Until another thread calls the object's notify() to wake up the thread, it can continue to acquire the object lock and continue execution. The corresponding notify() is the release operation of the object lock. [Therefore, we can find that both the wait and notify methods can release the object's lock, but wait also releases CPU control, that is, the code behind it stops executing and the thread enters a blocked state, while the notify method does not release CPU control immediately, but The lock is automatically released after the execution of the corresponding synchronized(){} statement block ends. 】After releasing the lock, the JVM will select a thread among the threads waiting for resoure, grant it the object lock, wake up the thread, and continue execution. This provides synchronization and wake-up operations between threads. Both Thread.sleep() and Object.wait() can suspend the current thread and release CPU control. The main difference is that Object.wait() releases the object lock control while releasing the CPU, while in the synchronization block The Thread.sleep() method does not release the lock, only releases CPU control.

The above is the detailed content of How to use wait() and notify() methods in Java to operate instances of shared resources. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.