JAVA concurrent Programming-thread synchronous communication technology (lock and condition) (10)

Source: Internet
Author: User


in the previous blog, we have introduced the thread synchronization communication technology JAVA Concurrent Programming - traditional thread Synchronous communication technology (IV), the last article is the use of synchronized, wait , Notify to achieve, today we are using Lock and the Condition , let's combine the two comparisons to learn.

Simple lock lock application:


/** * Simple Lock application * @author Hejingyuan * */public class Locktest {public static void main (string[] args) {new locktest (). ini T ();} private void Init () {final Outputer outputer = new Outputer (); New Thread (New Runnable () {@Overridepublic void run () {while (t Rue) {try {Thread.Sleep],} catch (Interruptedexception e) {e.printstacktrace ();} Outputer.output ("Zhangxiaoxiang");}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {while (true) {try {Thread.Sleep]} catch ( Interruptedexception e) {e.printstacktrace ();} Outputer.output ("lihuoming");}}). Start ();} Static class Outputer{lock Lock = new Reentrantlock ();p ublic void output (String name) {int len = Name.length (); Lock.lock (); try{for (int i=0;i<len;i++) {System.out.print (Name.charat (i));} System.out.println ();} Finally{lock.unlock ();}}}


Lock is more object-oriented than the synchronied approach in the traditional threading model, and the lock itself should be an object as well as the lock itself. Two threads executing code snippets to achieve the effect of a synchronous mutex, they must be in the same lock object, which is in the internal method of the class that represents the resource to be manipulated. Instead of the thread code.

Attention:

Unlike synchronized, when a thread finishes executing, it closes the lock unlock (), and if it does not, the other waiting threads are locked out forever. Because the synchronized is implemented at the JVM level, the system can monitor the release of the lock, and Reentrantlock uses code to implement it, the system cannot automatically release the lock, and it needs to explicitly release the lock Lock.unlock () in the finally clause in the code.

Compare with previous blog (synchronous communication):

Implementation effect: The child thread Loop 10 times, then the main thread loop 100 times, and then back to the child thread loop 10 times, and then back to the main thread and loop 100 times, so loop 50 times


public class Conditioncommunication {public static void main (string[] args) {final business business = new Business ();//Create A thread and starts the new thread (new Runnable () {@Overridepublic void Run () {for (int i=1;i<=50;i++) {business.sub (i);}}). Start ();//Because the Mian method itself occupies a thread, the main thread does not need to be new threadfor (int i=1;i<=50;i++) {business.main (i);}}  Static class Business {lock lock = new Reentrantlock ();  Condition Condition = Lock.newcondition ();  Determines whether main executes or sub executes private Boolean bshouldsub = true; public void Sub (int i) {lock.lock ();//Lock up other threads cannot come in, including the following main () because they are using the same lock try{//bshouldsub==false while waiting while (!bshoul  DSub) {try {condition.await ();} catch (Exception e) {e.printstacktrace ();}  }for (int j=1;j<=10;j++) {System.out.println ("Sub thread sequence of" + j + ", loop of" + i);}  Bshouldsub = false;  Condition.signal ();  }finally{Lock.unlock ();  }} public void main (int i) {lock.lock (); try{//bshouldsub==true wait while (bshouldsub) {try {condition.await ();} catch (Exception e) {e.printsTacktrace ();} }for (int j=1;j<=100;j++) {System.out.println ("main thread sequence of" + j + ", loop of" + i);}  Bshouldsub = True;condition.signal ();  }finally{//If the exception is thrown in the middle, then the lock will not be unlocked, others will not enter//So write in finally inside the Lock.unlock (); }  }}}

In condition, replace wait () with await (), replace notify () with signal (), replace Notifyall () with Signalall (), and the traditional thread's way of communication, condition can be implemented.

The condition instance is essentially bound to a lock. To obtain an condition instance for a particular lock instance, use its newcondition () method.

Note: "Spurious wakeup" may occur while waiting for condition.

False Wakeup (Spuriouswakeup) when using conditional waits, we are using

while (condition not satisfied) {

Condition_wait (cond, mutex);

}

Instead of:

If (condition not satisfied) {

Condition_wait (Cond,mutex);

}

This is because there may be a false wake-up "spuriouswakeup" situation.

That is, even if no thread calls Condition_signal, the function that originally called condition_wait may return. At this point the thread is awakened, but the condition is not satisfied, this time if the condition is not checked and down, it may cause the subsequent processing error.

False wakeup should be avoided during system design, but this can affect the execution efficiency of the condition variable, and since the error caused by false wakeup can be avoided through the while loop, the logic of the program becomes the case of the while loop.

condition can control the sequence of runs between multiple threads


Condition is no different from traditional thread communication, and condition's power is that it can create different condition for multiple threads, which can control the order of operations between multiple threads.

For example:

Should be first on thread 1, thread 2, Build Condition Object 1:c_th1, Object 2:c_th2;

C_th1.await ()//block write thread 1

C_th2.signal ()//wake-up Read thread 2

-------

Otherwise, when a multi-threaded function has no arguments, how to specify which one to block, which to wake up, or more than 2 threads, always have a method specified.

Implement Demo ( with three threads, you want thread 1 running after thread 2, thread 2 running after running the thread 3, thread 3 runs after running thread 1):


public class Threeconditioncommunication {public static void main (string[] args) {final business business = new Business () ; New Thread (New Runnable () {@Overridepublic void Run () {for (int i=1;i<=50;i++) {business.sub2 (i);}}). Start (); New Thread (New Runnable () {@Overridepublic void Run () {for (int i=1;i<=50;i++) {business.sub3 (i);}}). Start (); for (int i=1;i<=50;i++) {business.main (i);}}  Static class Business {lock lock = new Reentrantlock ();  Condition condition1 = Lock.newcondition ();  Condition condition2 = Lock.newcondition ();  Condition Condition3 = Lock.newcondition ();  private int shouldsub = 1;  public void sub2 (int i) {lock.lock ();  try{while (shouldsub! = 2) {try {condition2.await ();} catch (Exception e) {e.printstacktrace ();}  }for (int j=1;j<=10;j++) {System.out.println ("Sub2 thread sequence of" + j + ", loop of" + i);}  Shouldsub = 3;  Condition3.signal ();  }finally{Lock.unlock ();  }} public void sub3 (int i) {lock.lock (); try{while (shouldsub! = 3) {try {COndition3.await ();}  catch (Exception e) {e.printstacktrace ();}  }for (int j=1;j<=20;j++) {System.out.println ("SUB3 thread sequence of" + j + ", loop of" + i);}  Shouldsub = 1;  Condition1.signal ();  }finally{Lock.unlock ();  }} public void main (int i) {lock.lock ();  try{while (shouldsub! = 1) {try {condition1.await ();} catch (Exception e) {e.printstacktrace ();} }for (int j=1;j<=100;j++) {System.out.println ("main thread sequence of" + j + ", loop of" + i);}  Shouldsub = 2;condition2.signal ();  }finally{Lock.unlock (); }  }}}

Summary:

for these two ways of implementing thread-synchronous communication, lock replaces the use of the Synchronized method and the statement, and Condition replaces the use of the Object monitor method. In contrast , Lock(itself an object) is more object-oriented, and condition can establish different condition for multiple threads, which can control the order of operations between multiple threads.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JAVA concurrent Programming-thread synchronous communication technology (lock and condition) (10)

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.