The art of Java Concurrent Programming (vi)--communication between threads

Source: Internet
Author: User

Data interactions are sometimes required between multiple threads, and the following describes the way data interactions between five threads are used, each of which has different usage scenarios.

1. Volatile, synchronized keywords

PS: For more information on volatile, please move to: The art of Java Concurrent Programming (iii)--volatile

1.1 How to achieve communication?

Both methods use synchronous mechanism to realize data communication between multiple threads. Rather than "communication", it is better to say "shared variables". When a shared variable is modified by volatile or wrapped by a synchronized block, their read and write operations directly manipulate the shared memory, so that each thread can see the most recent value of the shared variable, that is, the visibility of the memory.

1.2 Features
    • This approach is essentially "sharing data" rather than "passing data"; just from the result, the data seems to be passed from the write thread to the read thread;
    • This mode of communication cannot specify a particular receive thread. The operating system randomly determines which thread first accesses the data after it has been modified.
    • In general, this is not the real "communication", but "sharing".
1.3 Usage Scenarios

This way you can "pass" the variable. This can be used when you need to pass some common variables. For example, passing a Boolean flag that represents a state, passes a queue that stores all tasks, and so on.

1.4 Examples

The switch control of the thread is implemented in this way.

//used to control the current execution status of Threads  private  volatile  boolean  running = false ; //open a thread  Thread thread = new  thread (new  Runnable () {void  Run () {//switch  w        Hile  (!running) {thread.sleep (1000 );    } //perform thread task  dosometing (); }}). Start (); //start execution  public  void  start  () {running = true ;}  
2. How is the wait/notification mechanism 2.1 implemented?

The implementation of the wait/notification mechanism is done by Java, and we only need to invoke several methods of the object class.

    • Wait (): Changes the state of the current thread to "waiting state", joins the wait queue, releases the lock, and until the current thread breaks or calls the Notify method, the thread will be transferred from the waiting queue to the synchronization queue, at which point the competition lock can begin.
    • Wait (long): Just like the wait () function, there is only one more timeout action. Once it has timed out, it will continue executing the code after wait, and it will not throw a timeout exception!
    • Notify (): Transfers a thread in the wait queue to the synchronization queue.
    • Notifyall (): Transfers all threads in the wait queue to the synchronization queue.
2.2 Attention points
    • All of the above methods must be placed in the synchronization block;
    • And the above methods can only be called by the lock object of the synchronous block;
    • The Lock Object A.notify ()/notifyall () can only wake the thread of a wait by lock object A;
    • After calling the Notify/notifyall function, just move the thread from the wait queue to the blocking queue, and the thread will not return from the wait method until it competes with the lock, and then proceed to the next code;
2.3 QA
    • Why does wait have to be called in a synchronization block?
      Because the wait/notification mechanism needs to be used in conjunction with a shared state variable, it is generally a matter of checking the state first, and if the status is true, wait is included, which means "check and execute First", so the process needs to be locked to ensure its atomic execution.
      As an example:
//shared state variable   Boolean  flag = false ; //thread 1  Thread T1 = new  Thread (new  Runnable () {public  void  run  () { while  (!flag)        {Wait (); }}). Start (); //thread 2  Thread t2 = new  Thread (new  Runnable () {public  void  run  () {        Flag = true ;    Notifyall (); }}). Start ();  

The above example thread1 is not synchronized. When the THREAD1 executes to the while row, the state is determined to be true, at this point, if a context switch occurs, thread 2 starts execution, and the execution of a breath is finished, and flag is true, but thread1 continues execution, and waits after waiting to enter the wait state But there is no thread to wake it up, so wait.

    • Why does notify need to be locked? and must use the same lock as wait?
      First, the locking is to ensure the memory visibility of the shared variable so that it can be written directly to the shared memory after it has been modified so that the thread where wait is located is immediately visible.
      Second, the same lock is used with wait to ensure that wait and notify are mutually exclusive, that is: at the same moment, only one of the threads can execute.

    • Why do I have to call the wait function with a lock object of a synchronization block?
      First, because wait releases the lock, calling wait through the lock object tells wait which lock to release.
      Second, tell the thread which lock object you are waiting on, and only when the lock object calls notify can you be awakened.

    • Why do I have to call the Notify function using the lock object of a synchronization block?
      Tells notify that only the thread waiting on the lock object is awakened.

2.4 Code implementation

The wait/notify mechanism is used to implement producer and consumer patterns.

    • Producers
synchronized(锁A){    true;// 或者:list.add(xx);    锁A.notify();}
    • Consumers
synchronized(锁A){    // 不满足条件    while// 或者:list.isEmpty()        锁A.wait();    }    // doSometing……}
2.5 Timeout Wait mode

In the previous producer-consumer model, if the producer did not give notice, then the consumer would wait forever. In order to avoid this situation, we can increase the timeout waiting function for the consumer. This feature relies on the wait (long) method, which simply increments the time-out identifier in the check condition before wait, and is implemented as follows:

 Public voidGetLongMills) {synchronized (List){//Do not add timeout function        if(Mills <=0) { while(List. IsEmpty ()) {List. Wait (); }        }//Add timeout function        Else{Boolean istimeout =false; while(List. IsEmpty () && istimeout) {List. Wait (Mills); Istimeout =true; }//dosometing ...}    }}
3. Pipe Flow 3.1 effect

Pipeline flow is used to pass a byte stream or a character stream between two threads.

3.2 Features
    • The realization of pipeline flow relies on PipedOutputStream, PipedInputStream, PipedWriter, Pipedreader. Corresponds to byte stream and character stream respectively.
    • The difference between them and the IO stream is that the IO stream flows between the hard disk, memory, and socket, while the pipe flow flows only between two threads in memory.
3.3 implementation

The steps are as follows:
1. Create an input stream and an output stream in one thread, respectively;
2. Connect the input stream and the output stream;
3. Pass the input stream and output stream to two threads respectively;
4. Call the Read and write methods to enable inter-thread communication.

//Create an input stream and an output stream objectPipedWriter out =NewPipedWriter (); Pipedreader in =NewPipedreader ();//Connection input/output streamOut.connect (in);//Create a write thread class writethread extends Thread{    PrivatePipedWriter out; PublicWritethread (PipedWriter out) { This. out = out; } Public voidRun () {Out.write ("Hello concurrent world!"); }}//Create a read thread class readerthread extends Thread{    PrivatePipedreader in; PublicReaderthread (Pipedreader in) { This. in =; } Public voidRun () {in.read (); }}// 
4. join4.1 effect
    • A join can execute multiple threads concurrently executing in a sequential way;
    • The join function belongs to the thread class and is called through a thread object. When Threada.join () is executed in thread B, threads B will be blocked (the underlying call to the Wait method), and the Join method will not be returned until the Threada thread has finished running.
    • The thread being waited for can take a long time, so the join function throws interruptedexception. When Threada.interrupt () is called, the Join function throws the exception.
4.2 Implementation
publicstaticvoidmain(String[] args){    // 开启一条线程    new Thread(new Runnable(){        publicvoidrun(){            // doSometing        }    }).start();    // 调用join,等待t线程执行完毕    try{        t.join();    }catch(InterruptedException e){        // 中断处理……    }}

The art of Java Concurrent Programming (vi)--communication between threads

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.