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

Source: Internet
Author: User

Previous Article: Java thread (7)

I haven't updated the column "Java thread" in the last week, mainly because I am busy with my work this week and I am busy with my life. Well, I entered the topic. The previous article described the lock under the concurrent package, the lock can better solve the thread synchronization problem and make it more object-oriented, and readwritelock is more powerful in processing synchronization, so it is also not enough for threads to be mutually exclusive and communication is required, the content of this article is based on the previous article, how to use lock to process thread communication.

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:

public class ThreadTest2 {public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {@Overridepublic 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.notify();} 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.notify();} 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.

Class boundedbuffer {final lock = new reentrantlock (); // Lock Object final condition notfull = lock. newcondition (); // write the thread condition 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. await (); // blocked write thread items [putptr] = x; // assign the value 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 (); // blocked 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. Wake up onlyRead thread blocking queueOne of them;

6. Execute a read thread and call the take method;

7 .......

8. Wake up onlyWrite thread blocking queue.

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.

This article is from: Gao Shuang | coder, original address: http://blog.csdn.net/ghsau/article/details/7481142.

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.