Java thread (8): Condition-more efficient thread Communication Mode

Source: Internet
Author: User

Then, Condition and Condition introduce the main character of this Article. They break down the Object monitor method (wait, policy, and policyall) into completely different objects so that they can be combined with any Lock implementation, multiple waiting sets (wait-set) are provided for each object ). Here, Lock replaces the use of synchronized methods and statements, and Condition replaces the use of Object monitor methods. The following code replaces a previously written thread communication example with Condition (Java thread (3:
[Java]
Public class ThreadTest2 {
Public static void main (String [] args ){
Final Business business = new Business ();
New Thread (new Runnable (){
@ Override
Public void run (){
ThreadExecute (business, "sub ");
}
}). Start ();
ThreadExecute (business, "main ");
}
Public static void threadExecute (Business business, String threadType ){
For (int I = 0; I <100; I ++ ){
Try {
If ("main". equals (threadType )){
Business. main (I );
} Else {
Business. sub (I );
}
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}
Class Business {
Private boolean bool = true;
Private Lock lock = new ReentrantLock ();
Private Condition condition = lock. newCondition ();
Public/* synchronized */void main (int loop) throws InterruptedException {
Lock. lock ();
Try {
While (bool ){
Condition. await (); // this. wait ();
}
For (int I = 0; I <100; I ++ ){
System. out. println ("main thread seq of" + I + ", loop of" + loop );
}
Bool = true;
Condition. signal (); // this. equaly ();
} Finally {
Lock. unlock ();
}
}
Public/* synchronized */void sub (int loop) throws InterruptedException {
Lock. lock ();
Try {
While (! Bool ){
Condition. await (); // this. wait ();
}
For (int I = 0; I <10; I ++ ){
System. out. println ("sub thread seq of" + I + ", loop of" + loop );
}
Bool = false;
Condition. signal (); // this. equaly ();
} Finally {
Lock. unlock ();
}
}
}
In Condition, await () is used to replace wait (), signal () with policy (), and signalAll () with policyall (). In the traditional thread communication mode, condition can be implemented. Note that Condition is bound to the Lock. The newCondition () method must be used to create a Lock.
In this case, there is no difference between Condition and traditional thread communication. The power of Condition is that it can create different Condition for multiple threads. Next we will introduce a piece of code in the API to illustrate it.
[Java]
Class BoundedBuffer {
Final Lock lock = new ReentrantLock (); // Lock Object
Final Condition notFull = lock. newCondition (); // write thread Conditions
Final Condition notEmpty = lock. newCondition (); // read thread Condition
 
Final Object [] items = new Object [100]; // cache queue
Int putptr/* write Index */, takeptr/* read Index */, count/* Number of data in the queue */;
 
Public void put (Object x) throws InterruptedException {
Lock. lock ();
Try {
While (count = items. length) // If the queue is full
NotFull. await (); // blocking the write thread
Items [putptr] = x; // value assignment
If (++ putptr = items. length) putptr = 0; // if the write index is written to the last position of the queue, set it to 0.
+ + Count; // number + +
NotEmpty. signal (); // wake up the read thread
} Finally {
Lock. unlock ();
}
}
 
Public Object take () throws InterruptedException {
Lock. lock ();
Try {
While (count = 0) // If the queue is empty
NotEmpty. await (); // block the read thread
Object x = items [takeptr]; // Value
If (++ takeptr = items. length) takeptr = 0; // if the read index reads the last position of the queue, it is set to 0.
-- Count; // number --
NotFull. signal (); // wake up the write thread
Return x;
} Finally {
Lock. unlock ();
}
}
}
This is a cache area in a multi-threaded working environment. The cache area provides two methods: put and take. put means to store data, take means to retrieve data, and there is a cache queue in it, for more information about the variables and methods, see the code. This cache class provides the following functions: multiple threads store data in and retrieve data from the cache Queue (first, then, and then) the maximum value that can be cached is 100. Multiple Threads are mutually exclusive. When the value stored in the cache queue reaches 100, the write thread is blocked and the read thread is awakened, when the value stored in the cache queue is 0, the read thread is blocked and the write thread is awakened. The following describes the Code Execution Process:
1. A write thread executes and calls the put method;
2. Check whether the count value is 100. Obviously there is no 100;
3. Continue execution and save the value;
4. After determining whether the index location being written is equal to 100, the index value is changed to 0 and the count + 1 value is changed;
5. Only one of the read thread blocking queues is awakened;
6. Execute a read thread and call the take method;
7 .......
8. only wake up the write thread to block one of the queues.
This is the power of multiple conditions. If the cache queue is full, the blocking must be a write thread, and the wake-up must be a read thread. On the contrary, the blocking must be a read thread, the wake-up process must be a write thread. If there is only one Condition, what is the effect? The cache queue is full. This Lock does not know whether to wake up the read thread or write thread, it is a great pleasure to wake up the read thread. If it is a write thread, the thread will be awakened and blocked again, and then wake up again, which wastes a lot of time.

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.