Java multithreaded Programming Core technology reading notes (3)-Thread communication

Source: Internet
Author: User

Threads are independent individuals in the operating system, but these individuals cannot be a whole without special treatment. Inter-thread communication can realize the inter-thread information interchange, mutual arousal and other functions, the system is more interactive, greatly improve the CPU utilization, but also allows developers to have clear control and supervision of the various thread tasks, the most common thread communication method is the-wait/notification mechanism.

One, wait/notification mechanism 1, wait ()/notify ()

The wait/notice mechanism is ubiquitous in life, such as the chef/Waiter's menu delivery station, producer/consumer mode, and the wait/notification mechanism is implemented through the two method wait ()/notify () in the JDK.

The function of the wait () method is to cause the thread that is currently executing the code to wait, place it in the pre-execution queue, and stop execution at the code where wait () immediately releases the lock held until it is notified or interrupted. The wait () method must be placed in a synchronous method or code block, and the illegalmonitorstateexception will be thrown when run;

The method Wait (long) is waiting for a certain period of time, if the thread is automatically awakened;

Method Notify () also needs to be executed within a synchronous method or code block, and the runtime throws Illegalmonitorstateexception, which notifies other threads that might wait for the lock held by the object, if there are multiple waiting threads, Randomly picks a wait-state thread to get the lock on the object, but does not release the lock immediately, but waits until the thread executes the synchronization method or synchronizes the code block before releasing the lock ;

The method Notifyall () is the same as notify (), except that it wakes up all waiting threads waiting for the resource , enters into a running state, which thread obtains the lock, depending on the JVM implementation, which may be the highest priority or random;

Use Wait ()/notify () to implement producer/consumer mode (storage of shared resources with the stack of operations):

Operation Stack Implementation: Mystack.java

 Public classMystack {PrivateList List =NewArraylist<>(); synchronized  Public voidpush () {Try {            //to prevent multiple producers from causing list.size () >1, the If is not used, but while             while(list.size () = = 1) {System.out.println ("Push operation:" + Thread.CurrentThread (). GetName () + "Thread wait state");  This. Wait (); } list.add ("Antstring=" +math.random ()); //In order to prevent multi-producer, wake Up is the same kind is not heterogeneous and caused by suspended animation, should be used Notifyall (), the same             This. Notifyall (); System.out.println ("Push=" +list.size ()); } Catch(interruptedexception e) {e.printstacktrace (); }    }    synchronized  Publicstring Pop () {string temp= ""; Try {             while(list.size () = = 0) {System.out.println ("Pop operation:" + Thread.CurrentThread (). GetName () + "Thread wait state");  This. Wait (); } temp= "" + list.get (0); List.remove (0);  This. Notifyall (); System.out.println ("Pop=" +list.size ()); } Catch(interruptedexception e) {e.printstacktrace (); }        returntemp; }}

Producer Realization: Producer.java

 Public class Producer {    private  mystack mystack;      Public Producer (Mystack mystack) {        Super();         this. mystack = mystack;    }      Public void Pushservice () {        mystack.push ();    }}

Producer Thread implementations: Producerthread.java

 Public class extends Thread {    private  Producer Producer;      Public Producerthread (Producer Producer) {        Super();         this. Producer = producer;    }    @Override    publicvoid  run () {        while (true  ) {            producer.pushservice ();     }}}

Consumer realization: Customer.java

 Public class Customer {    private  mystack mystack;      Public Customer (Mystack mystack) {        Super();         this. mystack = mystack;    }      Public void Popservice () {        mystack.pop ();    }}

Consumer Threading Implementation: Customerthread.java

 Public class extends Thread {    private  customer customer;      Public Customerthread (Customer customer) {        Super();         this. Customer = customer;    }    @Override    publicvoid  run () {        while (true  ) {            customer.popservice ();     }}}

Run class: Run.java

//single producer-single consumer Public classRun { Public Static voidMain (string[] args) {mystack mystack=NewMystack (); Producer Producer=NewProducer (Mystack); Customer Customer=NewCustomer (Mystack); Producerthread ProducerThread1=NewProducerthread (producer); Customerthread CustomerThread1=NewCustomerthread (customer);        Producerthread1.start ();    Customerthread1.start (); }}
2. Pipeline Communication

A variety of input/output stream streams are available in Java, where pipeline flow (Pipestream) is a special kind of flow that can be used to transfer data directly between different threads.

Two streams are available in the Java JDK-4 classes to enable communication between threads:

1, Byte stream (PipedInputStream and PipedOutputStream)

2. Character stream (Pipedreader and PipedWriter)

Code Demo Temporary ...

Ii. use of Join () 1, join ()

In many cases, the main thread creates and starts a child thread, and if the child thread executes for a long time, the main thread will end up earlier than the child thread. If you want the main thread to wait for the child thread to end, you can use the join () method.

The sample code is as follows: Test.java

classMyThread3extendsThread {@Override Public voidrun () {Try{System.out.println (System.currenttimemillis ()+ "I am a child thread and I need to sleep for a while!" "); Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); }    }} Public classTest { Public Static voidMain (string[] args) {Try{MyThread3 MyThread=NewMyThread3 ();            Mythread.start ();            Mythread.join (); System.out.println (System.currenttimemillis ()+ "I am the main thread, end after the end of the child thread!" "); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Output:

1493215918686    I am a child thread, I need to sleep for a while! 1493215923705 I am the main thread, the end   of the child thread after the end!

You can see that the main thread is really waiting for the child thread to sleep () before the end of 5s!

2. The difference between join (long) and sleep (long)

The function of the method join (long) is how long the current thread waits at least for that thread, and if the thread ends before the time, the method is the same as the sleep gas. However, the function of the method join (long) is implemented internally using the wait (long) method, so the join (long) method has the feature of releasing the lock, and can look at the implementation code of the Join (long):

 Public Final synchronized voidJoinLongMillis)throwsinterruptedexception {LongBase =System.currenttimemillis (); Longnow = 0; if(Millis < 0) {            Throw NewIllegalArgumentException ("Timeout value is negative"); }        if(Millis = = 0) {             while(IsAlive ()) {Wait (0); }        } Else {             while(IsAlive ()) {LongDelay = Millis-Now ; if(Delay <= 0) {                     Break;                } wait (delay); now= System.currenttimemillis ()-Base; }        }    }
Third, the use of threadlocal/inheritablethreadlocal 1, ThreadLocal

Static variables can be used together by all threads, and threadlocal allows each thread to maintain its own value. Threadlocal can be likened to a box that holds data globally, and the box can hold private data for each thread.

2, Inheritablethreadlocal

functionality is similar to threadlocal, but inheritablethreadlocal can allow child threads to inherit the values placed in the parent thread, but can also be modified without affecting the parent thread.

Java multithreaded Programming Core technology reading notes (3)-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.