Java Sync lock mechanism Wait () notify () Notifyall ()

Source: Internet
Author: User

Wait () notify () Notifyall ( ) These 3 methods are used to coordinate the access of multiple threads to shared data, so they must be used in the synchronized statement block.

  Wait () must be inside the synchronized function or code block, and wait () causes the thread that has already obtained the synchronized function or code block control to temporarily rest and lose control, Because the phenomenon loses control and enters the wait, other threads can take control and, where appropriate, invoke Notifyall () to wake the thread of Wait (). It should be noted that the awakened thread has lost control and other threads can take advantage of it, so the use of wait () must be over 2 threads, and the threads in wait () must be awakened under different conditions.

  Notifyall () does not allow the current thread to give up control at once, but only to let other threads in wait () wake up, so although I wake you up, you have to wait until I run out of the warehouse to get in.

Example: The synchronization mechanism shared by producers and consumers.

ProductList is a product warehouse, when the warehouse is full, the producer thread needs wait (), thereby abandoning the control of the product warehouse, this time the consumer thread can come in and get control of the warehouse, once the consumer consumes the product, the warehouse is no longer full, At this point the consumer thread has the Notifyall () Producer thread to wake up the waiting producer thread, but the producer does not immediately make the production and needs to wait for the consumer thread to end the operation in order to regain control of the warehouse before production.

  //Product class   
public class Product {
int id;
Private String Producedby = "n/a";
Private String Consumedby = "n/a";

//Specify producer name
Product (String producedby) {
This.producedby = Producedby;


//Specify consumer name
public void consume (String consumedby) {
This.consumedby = Consumedby;


Public String toString () {
Return ' product, producer = ' +producedby + ', consumer = ' +consumedby;
}
Public String Getproducedby () {
return producedby;

public void Setproducedby (String producedby) {
This.producedby = Producedby;


Public String getconsumedby () {
return consumedby;

public void Setconsumedby (String consumedby) {
This.consumedby = Consumedby;
}
}



//Warehouse class
public class ProductList {
int index = 0;
product[] ProductList = new Product[6];

Producers Store Products
Public synchronized void push (product product) {
The warehouse is full.
while (index = = productlist.length) {
try {
System.out.println ("" +product.getproducedby () + "is waiting.");
Wait ();
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
Notifyall () will continue to execute until the completion
Productlist[index] = product;
index++;
System.out.println (index+ "" + product.getproducedby () + "produced:" +product);
Notifyall ();
System.out.println ("" +product.getproducedby () + "send a Notifyall ().");
}


Consumers take out products
Public synchronized Product pop (String consumename) {
while (index ==0) {//Warehouse empty
try {
System.out.println ("+consumename+" is waiting. ");
Wait ();
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}

will continue to do the same.
index--;
Product Product = Productlist[index];
Product.consume (Consumename);
System.out.println (index+ "" +product.getconsumedby () + "consumed:" +product);
Notifyall ();
return product;
}
}

Producer Class
public class Producer implements Runnable {
String name;
ProductList PS = null;
Producer (productlist ps,string name) {
This.ps = PS;
THIS.name = name;
}

public void Run () {
while (true) {
Product Product = new product (name);
Ps.push (product);
try {
Thread.Sleep ((int) (Math.random () * 200));
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}

Consumer class
 public class Consumer implements runnable{
String name;
ProductList PS = null;

Consumer (productlist PS, String name) {
This.ps = PS;
THIS.name = name;
}

@Override
public void Run () {
while (true) {
Ps.pop (name);
try {
Thread.Sleep ((int) math.random () *));
}catch (interruptedexception e) {
E.printstacktrace ();
}
}
}
}


//test class

public class Test {
public static void Main (string[] args) {
ProductList PS = new ProductList ();
Producer px = new Producer (PS, "producer X");
Producer py = new Producer (PS, "producer Y");

Consumer CA = new Consumer (PS, "consumer a");
Consumer cb = new Consumer (PS, "consumer B");
Consumer cc = new Consumer (PS, "Consumer C");

New Thread (px). Start ();
New Thread (PY). Start ();
New Thread (CA). Start ();
New Thread (CB). Start ();
New Thread (CC). Start ();
}

}


Java Sync lock mechanism Wait () notify () Notifyall ()

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.