Talking about the wait and notify and sleep of multithreading

Source: Internet
Author: User
Tags int size

Before calling Wait (), the thread must obtain an object-level lock on the object, that is, the wait () method can only be invoked in the synchronization method or in the synchronization block. After the wait () method is executed, the current thread releases the lock and stops execution from wait (). The thread competes with other threads to regain the lock before returning from Wait (). Throws a illegalmonitorstateexception if the appropriate lock is not held when the wait () is invoked.


The method Notify () is also called in a synchronous method or a synchronization block, that is, the thread must also obtain an object-level lock on the object before it is invoked. If you do not hold the appropriate lock when calling notify (), the illegalmonitorstateexception is also thrown. This method is used to notify other threads that may wait for an object lock on the object, and if more than one thread waits, the thread planner randomly picks one of the wait-state threads, notifies it notify, and waits for the object lock to get it. What needs to be explained is that after the Notify () method is executed, the current thread does not immediately release the object lock, nor does the wait state thread immediately acquire the object lock until the execution of the Notify () The thread of the method finishes the current statement program (if the notify in the loop executes the statement in the current loop block and wakes up another waiting thread) the current thread releases the lock, and the thread in which the wait state resides can get the object lock. When the first wait thread that gets the lock on the object is finished running, it frees the object lock, and if the object does not use the Notify statement again, the other wait-state thread will continue to block in the waiting state, even if the object is already idle, because the object is not being notified. Until this object emits a notify or notifyall.

Red font section See Code Analysis and parsing

Package test;
Import java.util.ArrayList;

Import java.util.List;

	 public class test6{Private list<string>list=new arraylist<string> ();
	 public void Add () {List.add ("root");
	 public int size () {return list.size (); 
		 public static void Main (string[] args) {final Test6 list=new Test6 (); 
		 
		 Final Object Lock=new object (); Thread Threada=new thread () {public void run () {try{synchronized (lock) {if (List.size ()!=5) {Sys
					  TEM.OUT.PRINTLN ("Wait Begin" +system.currenttimemillis ());
				  The statement following the lock.wait ()//wait () stops execution of the current lock System.out.println ("Wait-end" +system.currenttimemillis ());
		 }}catch (Exception e) {}}};
		 
		 
		 Threada.start ();
						  Thread Threadb=new thread () {public void run () {try{synchronized (lock) {for (int i=0;i<10;i++) {
						  List.add ();
						  System.out.println ("added" + (i+1) + "element"); if (List.size () ==5) {lock.notify ();/notify will continue to execute the following statements before releasing the current lock System.out.println ("I have given a wake-up call");
					  } thread.sleep (1000);
		 }}catch (Exception e) {}}};
	 Threadb.start ();

 }

}


The difference between sleep and wait
The first thing to understand is that locks in multiple threads are object-level, not thread-level, so wait,notify,notifyall can only be invoked in objects (locks) in the synchronization block, and the sleep thread object (such as thread) calls
So if you call the method in object, the wait method can cause blocking, only waiting for the appropriate object to call the
Notify or Notifyall will then become operational to regain CPU execution time, if the monotony of the sleep method is not affected by the lock, because sleep is in thread, the Sleep method call will not release the lock, but the wait method will release the lock, But both wait and sleep cause the thread to suspend the CPU execution, and the OS is reassigned to another thread.


Sleep lets threads end from "Running"-> "blocking state" time/interrupt-> "runnable"
Wait lets the thread retrieve the lock identity from the "Running"-> "Waiting queue" notify-> "Lock Pool"->-"runnable"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.