Java Thread (ix): condition-more efficient way to thread communication

Source: Internet
Author: User

Original: http://blog.csdn.net/ghsau/article/details/7481142

Nearly a week did not update the "Java Thread" column, mainly this week work more busy, life is also busy, hehe, into the topic, the previous chapter on the Lock,lock can better solve the thread synchronization problem, make it more object-oriented, And Readwritelock is more powerful when it comes to synchronizing, then again, it is not enough to have a mutual exclusion between threads, but also to communicate, this article is based on the previous article, using lock how to handle thread communication.

So introducing the protagonist of this article, condition,condition the object monitor method (wait, notify, and Notifyall) into distinct objects to provide multiple waits for each object by combining these objects with any Lock implementation Set (Wait-set). 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:

[Java]View Plaincopy
  1. Public class ThreadTest2 {
  2. public static void Main (string[] args) {
  3. final Business business = new Business ();
  4. New Thread (new Runnable () {
  5. @Override
  6. public Void Run () {
  7. Threadexecute (Business, "Sub");
  8. }
  9. }). Start ();
  10. Threadexecute (Business, "main");
  11. }
  12. public static void Threadexecute (Business business, String Threadtype) {
  13. For (int i = 0; i < ; i++) {
  14. try {
  15. if ("main". Equals (Threadtype)) {
  16. Business.main (i);
  17. } Else {
  18. Business.sub (i);
  19. }
  20. } catch (Interruptedexception e) {
  21. E.printstacktrace ();
  22. }
  23. }
  24. }
  25. }
  26. Class Business {
  27. private Boolean bool = true;
  28. Private Lock lock = new Reentrantlock ();
  29. private Condition Condition = Lock.newcondition ();
  30. public /*synchronized*/ void main (int loop) throws interruptedexception {
  31. Lock.lock ();
  32. try {
  33. While (bool) {
  34. Condition.await ();  //this.wait ();
  35. }
  36. For (int i = 0; i < ; i++) {
  37. SYSTEM.OUT.PRINTLN ("main thread seq of" + i + ", loop of" + loop);
  38. }
  39. bool = true;
  40. Condition.signal ();  //this.notify ();
  41. } finally {
  42. Lock.unlock ();
  43. }
  44. }
  45. public /*synchronized*/ void sub (int loop) throws interruptedexception {
  46. Lock.lock ();
  47. try {
  48. While (!bool) {
  49. Condition.await ();  //this.wait ();
  50. }
  51. For (int i = 0; i < i++) {
  52. System.out.println ("Sub thread seq of" + i + ", loop of" + loop);
  53. }
  54. BOOL = false;
  55. Condition.signal ();  //this.notify ();
  56. } finally {
  57. Lock.unlock ();
  58. }
  59. }
  60. }

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.

[Java]View Plaincopy
  1. Class Boundedbuffer {
  2. Final Lock lock = new Reentrantlock (); Lock Object
  3. final Condition notfull = Lock.newcondition (); //write thread condition
  4. final Condition notempty = Lock.newcondition (); //Read thread condition
  5. final object[] items = new object[]; Cache queue
  6. int putptr/* Write index */, TAKEPTR/* Read Index */, Count*/* Number of data present in queue */;
  7. public void put (Object x) throws interruptedexception {
  8. Lock.lock ();
  9. try {
  10. While (count = = items.length)//If the queue is full
  11. Notfull.await (); //Block write thread
  12. ITEMS[PUTPTR] = x; //Assigned value
  13. if (++putptr = = items.length) Putptr = 0; If the write index is written to the last position in the queue, then set to 0
  14. ++count; //number + +
  15. Notempty.signal (); //wake-up Read thread
  16. } finally {
  17. Lock.unlock ();
  18. }
  19. }
  20. Public Object Take () throws interruptedexception {
  21. Lock.lock ();
  22. try {
  23. While (count = = 0)//If the queue is empty
  24. Notempty.await (); //block read thread
  25. Object x = items[takeptr]; //value
  26. if (++takeptr = = items.length) Takeptr = 0; If the read index is read to the last position in the queue, then set to 0
  27. --count; //number--
  28. Notfull.signal (); //wake-up Write thread
  29. return x;
  30. } finally {
  31. Lock.unlock ();
  32. }
  33. }
  34. }

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 is the power of multiple condition, assuming that the cache queue is full, then the blocking is definitely a write thread, wake Up is definitely a read thread, on the contrary, the blocking is definitely a read thread, the wake is definitely a write thread, then assume that only one condition will have what effect? Cache queue is already full, this lock does not know whether to wake up the read thread or write thread, if the wake is a read thread, happy, if the wake is a write thread, then the line Cheng Gang is awakened, and is blocked, then to wake up, so that wasted a lot of time.

Java Thread (ix): condition-more efficient way to thread communication

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.