Thread synchronization and yield (), wait (), Notify (), Notifyall ()

Source: Internet
Author: User
Tags thread class

One, thread synchronization

1, the purpose of thread synchronization is to protect multiple threads to access a resource when the resource is destroyed. 2, thread synchronization method is implemented by the lock, each object has a cut only a lock, the lock with a specific object, the thread once the object lock, the other access to the object's thread can no longer access the object's other synchronization methods. Ii. Two methods for realizing the synchronization mechanism1. Synchronizing code blocks:
Synchronized (same data) {} The same data: N threads access one data at the same time.
2.
Synchronization method:
Public synchronized Data Return type method name () {}
is to use synchronized to decorate a method, the method is called a synchronous method. For a synchronous method, there is no need to display the specified synchronization monitor, the synchronization monitor of the synchronous method is this that is the object itself (in this case the object itself is a bit vague, it is actually called the object of the synchronization method) by using the synchronous method, it is very convenient to turn a class into a thread-safe class, with the following characteristics:
1, objects of this class can be accessed by multiple threads safely.
2, after each thread invokes any method of the object, it will get the correct result.
3, after each thread invokes any method of the object, the object's state remains in a reasonable state.
Note: The Synchronized keyword can be used to modify a method, or to decorate a block of code, but not to decorate constructors, properties, and so on.
realize the synchronization mechanism note the following points: High security, low performance, in multi-threaded use. High performance, low security, in single-threaded use. The key code is as follows:writing a printer class: Printer defines two methods
 PackageCn.d.happy; Public classPrinter {Object o=NewObject (); //or add synchronized before void     Public voidprint1 () {//Synchronizing code blocks         synchronized(o) {System.out.print (Line); System.out.print (Drive); System.out.print (With); System.out.print (Step);    System.out.println (); }    }     Public voidPrint2 () {synchronized(o) {System.out.print (Oh); System.out.print (Oh);    System.out.println (); }    }}

Define two thread classes and override the Run method. Inherits the thread and implements the Runnable interface through the For loop traversal count

 Package Cn.d.happy;  Public class extends thread{    public  Printer print;        @Overridepublicvoid  run () {    // must have an object instance    of this class  for (int i = 1; I <=10; i++) {        print.print1 ();     }}}
 Package Cn.d.happy;  Public class Implements runnable{    public  Printer print;    @Override    publicvoid  run () {         for (int i = 1; I <=10; i++) {             print.print2 ();             }}}

The test class creates a printer object and two thread objects and assigns values

 PackageCn.d.happy; Public classTest { Public Static voidMain (string[] args) {//Buy a printerPrinter p=NewPrinter (); //Create the first thread object and assign a value to the propertyMyThread t1=NewMyThread (); T1.print=p;            T1.start (); //03. Create a second thread object and assign a value to the propertyMyThread2 t2=NewMyThread2 (); T2.print=p; Thread TT=NewThread (T2); Tt.start ();}}

Implementation results:

Third, Java multi-thread yield (), wait (), Notify (), Notifyall ()

Yield (),

1) through the yield () function, the thread can be entered into an executable state, and the scheduler will be re-scheduled from the thread in the executable state. So the function that called yield () is also likely to be executed immediately.
2) when the yield () function is called, the thread does not release its "lock Flag".

classTestthreadmethodextendsthread{ Public Static intSharevar = 0;  PublicTestthreadmethod (String name) {Super(name); }         Public synchronized voidrun () { for(inti=0; i<4; i++) {System.out.print (Thread.CurrentThread (). GetName ()); System.out.println (" : " +i);            Thread.yield (); }        }    }     Public classtestthread{ Public Static voidMain (string[] args) {Testthreadmethod T1=NewTestthreadmethod ("T1"); Testthreadmethod T2=NewTestthreadmethod ("T2");            T1.start (); T1.start (); //(1)//T2.start (); (2)}

The result of the operation is:
t1:0
t1:1
T1:2
T1:3
t1:0
t1:1
T1:2
T1:3
When you call yield () from the result, the object's "lock flag" is not freed.
If you comment out the code (1) and remove the comment from the Code (2), the result is:
t1:0
t1:1
t2:0
T1:2
t2:1
T1:3
T2:2
T2:3
The result shows that although the T1 thread called Yield (), it was executed immediately.  

wait and notify are an important part of the Java synchronization mechanism. Combined with synchronized keyword use, you can build many excellent synchronization models.
synchronized (this) {} is equivalent to publicsynchronized void method () {...}
synchronization is divided into class level and object level, which correspond to class lock and object lock respectively. Class locks are only one per class, and if the static method is modified by the Synchronized keyword, the class lock must be obtained before the method is executed; object locks are similar.
first, when you invoke the wait and Notify/notifyall of an object, you must ensure that the calling code is synchronous with the object, that is, it must be equal to synchronized (obj) {...} To call obj's wait and notify/notifyall three methods, otherwise it will be an error:
java.lang.IllegalMonitorStateException:current Thread not owner
When you call wait, the thread automatically releases its occupied object lock and does not request an object lock. When the thread is awakened, it gets the right to acquire the object lock again.
So, there is not much difference between notify and Notifyall, except that notify only wakes up one thread and allows it to acquire a lock, Notifyall is to wake up all the threads waiting for the object and allow them to get the object lock, as long as the code in the Synchronied block , there is no object lock is unable to do. In fact, waking up a thread is a way to re-allow this thread to get the object lock and run down.

Notifyall, although it is called once for each wait object notify, but this is still in order, each object holds this waiting object chain, the order of the call is the order of the chain. In fact, it is also a thread to start the various threads in the waiting object chain, which needs to be noted in the specific application.

Wait (), notify (), Notifyall () are not part of the thread class, but belong to the object base class, which means that each pair has the function of Wait (), notify (), and Notifyall (). Because all have a lock on the image, the lock is the basis of each pair of image, of course, the method of operation lock is the most basic.

Wait ():

Wait for the object's synchronization lock, need to obtain the object's synchronization lock to call this method, otherwise the compilation can pass, but the runtime will receive an exception: Illegalmonitorstateexception.

Calling the Wait () method of an arbitrary object causes the thread to block, the thread cannot continue execution, and the lock on the object is freed.

Notify ():

Wake up the thread waiting for the object to synchronize the lock (wake only one, if there are multiple waits), note that when this method is called, it does not wake up the thread of a waiting state exactly, but is determined by the JVM to wake up which thread, and not by priority.

Calling the Notify () method of an arbitrary object causes a randomly selected unblocking in a thread that is blocked by calling the wait () method of the object (but is not really executable until the lock is acquired).

Notifyall ():

Wake up all waiting threads, notice that the thread that wakes up is notify before wait, and has no effect on the wait thread after notify.

In general, there is a need for coordination between multithreading: if the condition is not met, wait, and when the condition is met, the thread that waits for the condition is awakened. In Java, the implementation of this mechanism relies on wait/notify. The wait mechanism is closely related to the lock mechanism.

For example:

synchronized (obj) {  while (!   Condition) {obj.wait ();  } obj.dosomething (); }

When thread a obtains the obj lock, it finds that the condition condition is not satisfied and cannot proceed to the next processing, so thread A is wait ().
In another thread B, if B changes some conditions so that thread A's condition condition satisfies, it can wake up thread A:

Synchronizedtrue;  Obj.notify (); }

relationships between synchronized and wait (), notify () , and so on:  

1. There is not necessarily a wait,notify in a synchronized place.

2. There must be synchronized where there is wait,notify. This is because wait and notify are not thread classes, but are methods that each object has, and both methods are related to object locks, and there must be synchronized in place of locks.

Also, note that if you want to put the notify and wait methods together, you must call wait after calling notify, because if you finish calling wait, the thread is not currentthread.

Thread synchronization and yield (), 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.