The condition variables of Java multithreading technology

Source: Internet
Author: User

The previous article about the Lock,lock under the concurrent package can better solve the thread synchronization problem, make it more object-oriented, and readwritelock in the process of synchronization is more powerful, then the same, the thread is only mutually exclusive is not enough, also need to communicate, this article is based on the above, How to handle thread communication using lock.

So introducing the protagonist of this article, Condition, Condition the ObjectMonitor method (wait, notify, and Notifyall) into distinct objects, so that by combining these objects with any Lock implementation, Provides multiple wait set (Wait-set) for each object. Where Lock replaces the use of the Synchronized method and the statement, Condition replaces the use of the Object monitor method . The following example of a thread communication previously written is replaced with a condition implementation (Java thread (c)), the code is as follows:

1  Public classThreadTest2 {2      Public Static voidMain (string[] args) {3         FinalBusiness Business =NewBusiness ();4         NewThread (NewRunnable () {5 @Override6              Public voidrun () {7Threadexecute (Business, "sub"));8             }9 }). Start ();TenThreadexecute (Business, "main")); One     }     A      Public Static voidThreadexecute (Business business, String Threadtype) { -          for(inti = 0; I < 100; i++) { -             Try { the                 if("Main". Equals (Threadtype)) { - Business.main (i); -}Else { - business.sub (i); +                 } -}Catch(interruptedexception e) { + e.printstacktrace (); A             } at         } -     } - } - classBusiness { -     Private BooleanBOOL =true; -     PrivateLock lock =NewReentrantlock (); in     PrivateCondition Condition =lock.newcondition (); -      Public /*synchronized*/ voidMainintLoopthrowsinterruptedexception { to Lock.lock (); +         Try { -              while(bool) { theCondition.await ();//this.wait (); *             } $              for(inti = 0; I < 100; i++) {Panax NotoginsengSystem.out.println ("Main thread seq of" + i + ", loop of" +loop); -             } theBOOL =true; +Condition.signal ();//this.notify (); A}finally { the Lock.unlock (); +         } -     }     $      Public /*synchronized*/ voidSubintLoopthrowsinterruptedexception { $ Lock.lock (); -         Try { -              while(!bool) { theCondition.await ();//this.wait (); -             }Wuyi              for(inti = 0; I < 10; i++) { theSYSTEM.OUT.PRINTLN ("Sub thread seq of" + i + ", loop of" +loop); -             } WuBOOL =false; -Condition.signal ();//this.notify (); About}finally { $ Lock.unlock (); -         } -     } -}

In condition, replace wait () with await (), replace notify () with signal (), replace Notifyall () with Signalall (), traditional thread communication, condition can be implemented, here note, condition is bound to lock, the condition must be newcondition () method to create a lock.

In this view, condition and traditional thread communication is no different,the condition is that it can create different condition for multiple threads, the following introduces a piece of code in the API to illustrate.

1 classBoundedbuffer {2FinalLock lock =NewReentrantlock ();//Lock Object3FinalCondition notfull = Lock.newcondition ();//Write thread condition4FinalCondition notempty = Lock.newcondition ();//Read thread condition5 6Finalobject[] Items =NewOBJECT[100];//Cache Queue7intPutptr/*Write Index*/, takeptr/*Read Index*/, Count/*the number of data that exists in the queue*/;8 9 Public voidPut (Object x)throwsinterruptedexception {Ten Lock.lock (); OneTry { A while(count = = items.length)//if the queue is full -Notfull.await ();//Blocking Write Threads -ITEMS[PUTPTR] = x;//Assign Value theif(++putptr = = items.length) putptr = 0;//If the write index is written to the last position in the queue, then set to 0 -++count;//number + + -Notempty.signal ();//wake-up Read thread -}finally { + Lock.unlock (); -      } +    } A  at PublicObject Take ()throwsinterruptedexception { - Lock.lock (); -Try { - while(count = = 0)//if the queue is empty -Notempty.await ();//Blocking Read Threads -Object x = items[takeptr];//Take value inif(++takeptr = = items.length) takeptr = 0;//If the read index is read to the last position in the queue, then set to 0 ---count;//number-- toNotfull.signal ();//wake-up Write thread + returnx; -}finally { the Lock.unlock (); *      } $    } Panax Notoginseng}

This is a multi-threaded working environment of the buffer, buffer provides two methods, put and Take,put is the data, take is the data, there is a cache queue, the specific variables and methods described in the code, the buffer class implementation of the function: there are multiple threads to store data inside and fetch data from it, Its cache queue (FIFO first out) can cache the maximum value is 100, multiple threads are mutually exclusive, when the cache queue stored in the value of 100, the write thread block, and wake the read thread, when the cache queue is stored in the value of 0 o'clock, the read thread block, and wake the Write thread, The following is an analysis of the code execution process:

1. A write thread executes, calls the Put method;

2. Determine if count is 100, apparently not 100;

3. Continue execution, deposit value;

4. Determine if the current write index position + + is equal to 100, equality will write the index value to 0, and will count+1;

5. Only the wake-up read thread is blocking one of the queues;

6. A read thread executes, calling the Take method;

7 .....

8. Only the wake-up write thread is blocking one of the queues.

This article from: Gao | Coder, the original address: http://blog.csdn.net/ghsau/article/details/7481142, reprint please specify.

Conditional variables for Java multithreading technology

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.