Multi-Thread Wait,notify,volatile,synchronized,sleep

Source: Internet
Author: User
Tags volatile

Recently in learning multi-threading, now to summarize it. The first thing to do is to look at the following nouns.

(1) Wait: When the thread calls the Wait () method, the thread is currently in a blocking state and the lock is released and must be used in conjunction with synchronized when using the Wait method.

(2) Notify: When a thread calls the Notify () method, it wakes up a thread that is waiting for that object lock, does not release the lock , and must be used with synchronized when using the Notify method.

(3) Sleep: When the thread calls the sleep () method, it yields the CPU execution and does not release the lock . When the specified time is up, the running state is automatically restored.

(4) Volatile: visibility, the member variable it modifies is forced to reread the value of the member variable from memory each time it is accessed by the thread, and when the member variable changes, forcing the thread to write the change value back to the shared memory, so that at any moment two different threads always see the same value of a member variable. This is the guarantee of visibility. ( when multiple threads operate on the same member variable, the JVM copies a separate copy of each thread for efficiency , which causes dirty data to be read by the individual threads, so using the volatile keyword resolves the dirty data problem).

(5) Synchronized:synchronized for an operation or memory lock, it is mutually exclusive. When a thread wants to manipulate memory or operations that are synchronized decorated, it must first acquire a lock for subsequent operations , but only one thread at a time can get the same lock (object monitor), so it only allows one thread to operate.

(6) atomicity:  operations such as "A + = B" are not atomic, and "A + = B" In the JVM may take three steps:

(1) Remove A and B

(2) Calculation a+b

(3) Write calculation results to memory

If there are two threads t1,t2 are doing such an operation. T1 after the second step has not yet had time to write the data back into memory by the thread scheduler interrupted, so T2 began to execute, T2 after the completion of the T1 and did not complete the third step done. There was a mistake at this time, and the equivalent of T2 's calculation was ignored. So the above buy iodine tablets example before synchronizing the Add method, the actual result is always less than the expected result, because many operations are ignored. Similarly, operations such as "a++" are not atomic and need to be synchronized to achieve atomicity. The Java concurrent package provides some atomic classes, and we can read the API to understand the use of these atomic classes. For example: Atomicinteger, Atomiclong, atomicreference and so on.

  (7) The order in which the start () method is called does not represent the boot order of the thread, and the order in which the thread starts is nondeterministic.

write below In a simple example, thread T1 adds data to the collection list and notifies the T2 thread to add data to the collection when the size of the collection equals 5.

public class Listadd {//Collection public static volatile list<string> list=new arraylist<string> ();//Add elements to the collection public void Add () {List.add ("Gdpuzxs");} Returns the collection size public int size () {return list.size ();} public static void Main (String[]args) {final listadd listadd=new listadd ();//Create lock Final Object lock =new object ();// Thread T1thread t1=new Thread (new Runnable () {public void run () {System.out.println ("Enter T1"), synchronized (lock) {for (int i=0; i<10;i++) {listadd.add (); try {thread.sleep ();} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Current thread:" +thread.currentthread (). GetName () + "added an element"); if (Listadd.size () ==5) { System.out.println ("Wake Up notification! "); Lock.notify ();}}}}," T1 ");//thread T2thread t2=new thread (new Runnable () {public void run () {System.out.println (" Enter T2 ") ; synchronized (lock) {if (Listadd.size ()!=5) {try {lock.wait ();} catch (Interruptedexception e) {e.printstacktrace ()}} System.out.println ("Current thread:" +thread.currentthread (). GetName () + "already notified! "); for (int i=0;i<5;i++) {Listadd.add (); System.out.println ("Current thread:" +thread.currentthread (). GetName () + "added an element");}}}, "T2"); T2.start (); T1.start ();}}

  The results of the operation are as follows:

  

  Analysis Result: The above two different result sets appear on multiple runs. (The order that the start () method is called does not represent the boot order of the thread, and the order in which the threads are started is nondeterministic. )

Result (1): Thread T2 First grab the CPU operation right vote get the object lock, and then Judge size! =5, calls the Wait method, enters the blocking state, and releases the lock. The thread T1 gets the CPU operation right, adds 5 elements to the collection, Size=5 calls the Notify method to wake the thread T1, nofity continues to add 5 elements because the T1 method does not release the lock . When the T1 is finished, the lock is released, which is the T2 to continue adding 5 elements after the lock is taken.

  Result (2): Thread T1 First grabbed the CPU operation right vote got the object lock, and then added 5 elements, when size=5, called the Notify method (at this time T1 no thread in the blocking state, so call the method does not have any effect), and then T1 continue to add 5 elements. Release the lock when the T1 is finished executing. After T2 gets the object lock, it determines that size!=5 is true and calls the Wait method to enter the blocking state. The following code is not executed. The program has been in a running state.

This example causes a timeliness between threads because notify does not release the lock. That is, although T1 wakes T2, but because T1 does not release the lock, T1 executes the code inside the Synchronized method, and T2 acquires the lock to continue execution. You can use Countdownlatch to solve the problem of timeliness. The code is as follows:

  

public class ListAdd2 {//Collection public static volatile list<string> list=new arraylist<string> ();//Add elements to the collection public void Add () {List.add ("Gdpuzxs");} Returns the collection size public int size () {return list.size ();} public static void Main (String[]args) {final ListAdd2 listadd2=new ListAdd2 ();final Countdownlatch countdownlatch=new countdownlatch (1);Thread T1thread t1=new Thread (new Runnable () {public void run () {System.out.println ("enter T1"); for (int i=0;i<10;i++) { Listadd2.add (); try {thread.sleep ($);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Current thread:" +thread.currentthread (). GetName () + "added an element"); if (Listadd2.size () ==5) { System.out.println ("Wake Up notification! ");Countdownlatch.countdown ();}}}, "T1"),//thread T2thread t2=new thread (new Runnable () {public void run () {System.out.println ("Enter T2"), if (Listadd2.size ( ) {!=5) {try {countdownlatch.await ();} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println ("Current thread:" +thread.currentthread (). GetName () + "already notified! "); for (int i=0;i<5;i++) {listadd2.add (); System.out.println ("Current thread:" +thread.currentthread (). GetName () + "added an element"),}}, "T2"); T1.start (); T2.start ();}}

  The results are as follows: Use Countdownlatch.countdown (), countdownlatch.await () to release the lock.

  

Reference URL: http://www.cnblogs.com/mengyan/archive/2012/08/22/2651575.html

Multi-Thread Wait,notify,volatile,synchronized,sleep

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.