Java.lang.Object's wait and notify methods, and the role of keyword synchronized

Source: Internet
Author: User
Tags instance method

1. synchronized the role of

synchronizedSimilar to the critical section in Win32, the role of the critical section: for shared global variables, in the case of multiple threads concurrency, read-write to such a global variable will be read-write conflict,

The ability to read and write global variables can be executed atomically, rather than when a thread is reading the global data, because the thread is dispatched and the other thread is awakened at this time, changing the value of the global variable.

This makes the data obtained by the read thread unstable, so the code that reads and writes the global variables, we use the critical section to make the code atomized, and as long as the code in the critical section is executed atomically,

Instead of being interrupted by thread scheduling, it guarantees mutually exclusive access to the globally shared resource. For example:

Critical_section criticalsection; Critical section Object

1 DWORD WINAPI writethreadproc (lpvoid lpparameter)2 {  3     //Enter the critical section4EnterCriticalSection (&criticalsection); 5     //Write Resources6G_data =123;7     //leave the critical section8LeaveCriticalSection (&criticalsection); 9}
DWORD WINAPI readthreadproc (lpvoid lpparameter)  {      //    EnterCriticalSection (&criticalsection);        //      printf (g_data);     // leave the critical section    LeaveCriticalSection (&criticalsection);  }  

In the above example, in the critical section, the data is read and written, and no shared resource conflicts occur. Similarly, use keywords in Java synchronized to implement critical block blocks of code.

About synchronized How to use, refer to: Java synchronized detailed

2. Java.lang.notify method

Each object has a so-called object Monitor. Assume it is: Obj.monitor. A thread that can obtain a reference to an Obj object can register a listener on this object monitor (Obj.monitor) through the Obj.wait () method. All threads that call obj.wait are then added to the similar wait queue for the object.

JDK Document translation:

Wakes up a single thread waiting on this object monitor. If more than one thread waits on this object (that is, the thread executes obj.wait), it chooses to wake one of the threads. The selection is arbitrary (random) and occurs when a decision is made on the implementation. The thread wait waits on the object's monitor by calling one of the methods.

Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object.

This method should be called only by threads that are the owner of this object monitor. A thread can be the owner of this object Monitor (Obj.monitor) by one of the following three methods:

    • By executing the synchronous instance method of this object. (That is, an instance method with a keyword on the method signature, that is, synchronized executing Obj.instancemethod, and this method has a synchronized modifier)
    • The body of the statement that is synchronized by executing on this object synchronized . (The synchronized code block, that is synchronized (obj) {obj.wait (),} so that the code block has obj.monitor, you can call obj.wait)
    • For Class types of objects, you can do this by executing a synchronous static method of the class. (That is, the method signature has a synchronized keyword instance method, that is, the class-level method, that is, Obj.staticmehtod, and the signature of this method has synchronized keyword modification)

Only one thread can have a monitor for an object at a time.

In the above three cases, the thread has an object monitor (Obj.monitor) in which the Obj.notify method can be called.

The thread can become the owner of this object Monitor (Obj.monitor): The first case synchronization object is the this current instance object. So it can be called in this instance method: This.notify ();

In the third case, the synchronization object is ThreadTest.class.wait (); That is, the Notify method is called on the class object.

In the second case, since we can manually specify the object that specifies the monitor we want to get, this is not just the object of this and classname.class, it can be any other object, such as Waitobj, which is visible to all threads. Specifically designed to coordinate multi-threaded concurrency scenarios.

Java.lang.Object's wait and notify methods, and the role of keyword synchronized

Related Article

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.