Java Concurrency: Inter-thread communication and collaboration __java

Source: Internet
Author: User
Tags int size thread class
java Concurrency: Communication and collaboration between Threads

Summary:

threads and threads are not independent individuals, they need to communicate and collaborate with each other, and the most typical example is producer-consumer issues. This paper first introduces the wait/notify mechanism, and analyzes the two modes of--synchronized+wait-notify mode and lock+condition mode in detail to serve as the basis of communication and collaboration between threads. Further, with the classic producer-consumer issues as the background, proficient in the use of wait/notify mechanism. Finally, the join () method in the thread class is analyzed by source code, and the collaboration of host main thread and parasitic thread is illustrated. a primer.

Threads and threads are not independent individuals, and they need to communicate and collaborate with each other. For example, the most classic   producer-consumer model: When the queue is full, the producer needs to wait for the queue to continue to put the goods in, and during the waiting period, the producer must release the occupancy rights to the critical resource (i.e. the queue). Because producers do not release the right to use critical resources, then consumers can not consume the goods in the queue, there will be no space for the queue, then the producer will be indefinitely waiting. Therefore, in general, when the queue is full, the producer surrenders the critical resource and enters the suspend state. Then wait for the consumer to consume the goods, then the consumer informs the producer that there is room for the queue. Similarly, when the queue is empty, the consumer must wait, waiting for the producer to inform it that there is a product in the queue. This process of mutual communication is the collaboration between threads, which is also a problem to be discussed in this paper. &NBSP
 
In the following example, although two threads implement communication, it is a waste of the CPU by using thread B to continuously poll   by  while statements to detect a condition. Therefore, a mechanism is needed to reduce the waste of CPU resources, but also to achieve communication between multiple threads, that is, the  wait/notify mechanism  .

Resource Class class MyList {//Critical resource private volatile list<string> List = new arraylist<string> ();
    public void Add () {List.add ("abc");
    public int size () {return list.size ();

    }//Thread A class Threada extends thread {private MyList list;
        Public Threada (MyList list,string name) {super (name);
    This.list = list; @Override public void Run () {try {= 0; i < 3; i++) {list.a
                DD ();
                System.out.println ("added" + (i + 1) + "element");
            Thread.Sleep (1000);
        } catch (Interruptedexception e) {e.printstacktrace ();

    Thread B class Threadb extends thread {private MyList list;
        Public threadb (MyList list,string name) {super (name);
    This.list = list;
         @Override public for Void run () {try {while (true) {//a while statement polling       if (list.size () = = 2) {System.out.println ("==2), thread B is exiting."
                    ");
                throw new Interruptedexception ();
        A catch (Interruptedexception e) {e.printstacktrace ());

        Test public class Test {public static void main (string[] args) {MyList service = new MyList ();
        Threada a = new Threada (service, "a");

        THREADB B = new threadb (service, "B");
        A.start ();
    B.start ();
        }/* output (not unique): Added 1 elements added 2 elements ==2, thread B to exit. Java.lang.InterruptedException at Test.
     
     Threadb.run (test.java:57) adds 3 elements *///:~ 1 2 3 4
     
     5 6 7 8 9 10 11 12 13
   14 15 16 17 18 19 20 21  
     22 23 24 25 26 27 28 29 30
     
     31 32 33 34 35 36 37 38
     
     39 40 41 42 43 44 45 46 47
     
     48 49 50 51 52 53 54 55 56
     
     57 58 59 60 61 62 63 64
     
     65 66 67 68 69 70 71 72 73
     
     74 75 76 77 78 79 80 81 82
    
     83 84
two. Wait/notify mechanism

Prior to this, threads shared data to achieve communication, that is, multiple threads actively read a shared data, through synchronous mutual exclusion access mechanism to ensure thread security. The wait/notification mechanism is primarily guaranteed by the following three methods in the object class:

1. Wait (), notify () and Notifyall ()

All three of these methods are not the methods declared in the thread class, but the methods declared in the object class. The reason is that each object has a monitor (lock), so let the current thread wait for the lock of an object, of course, it should be manipulated through this object, rather than with the current thread, because the current thread may wait for the lock of multiple threads, and if it is done by threading, it is very complicated

1) Wait ()

Let the current thread (the thread returned by the Thread.concurrentthread () method) release the object lock and enter the wait (blocking) state.

(1) Method declaration

    Public final native void wait (long timeout) throws interruptedexception;
    
    
     
     1
    
    

(2) Method effect

Causes the current thread to wait until either another thread invokes the Notify () method or the Notifyall () method for th is object, or a specified amount of the time has elapsed. If any threads are waiting in this object, one of the them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on this object's monitor by calling one of the "Wait" () methods.

This method causes the "current thread" (Call it T):

①to place itself in the ' wait set ' for this object;

②to Relinquish (discard) any and all synchronization claims on this object;

③thread T becomes disabled for Thread scheduling purposes and lies dormant (hibernate) until one of four things happens:

Some other thread invokes the Notify method for this object and thread T happens to is arbitrarily chosen as the thread to be awakened;

Some other thread invokes the Notifyall to this object;

Some other thread interrupts thread T;

The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time isn't taken into consideration and the thread simply waits until notified (wait A time of 0 means waiting forever until the thread is awakened.

The thread T is then removed the ' wait set ' for the ' object ' and re-enabled for thread scheduling. It then competes in the usual manner and other threads for the right to synchronize on the object; Once it has gained control of the object, all its synchronization claims on the object are restored to the status quo -That's, to the situation as of the ' time ' is invoked. Thread T then returns from the invocation. Thus, on "return" from the "Wait Method", the synchronization state of the the object and the thread T is exactly as it were when th E wait method is invoked.

(3) method use conditions

This method should to called by a thread, that's the owner of this object.

(4) exception

Runtime (Unchecked) exception  
Illegalmonitorstateexception: if The current thread isn't the owner of this object ' s Monit OR;&NBSP
Illegalargumentexception: if The value of timeout is negative;

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.