Home >Java >javaTutorial >How to use wait() and notify() methods in Java to operate instances of shared resources

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

黄舟
黄舟Original
2017-10-11 09:52:411394browse

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