Java multithreading ~~~ Use Exchanger to exchange data between threads

Source: Internet
Author: User

Java multithreading ~~~ Use Exchanger to exchange data between threads

In multithreading, data exchange between two threads is very common. We can use a public data structure, and Java also provides a good

The Exchanger class can help us synchronize the data structure between two threads. Next we will use this class to implement

Now, the producer and consumer model seems to have been written down.


package com.bird.concursey.charpet5;import java.util.List;import java.util.concurrent.Exchanger;public class Producer implements Runnable {//This will be the data structure that the producer will interchange with the consumer.private List
 
   buffer;private Exchanger
  
   > exchanger;public Producer(List
   
     buffer, Exchanger
    
     > exchanger) {super();this.buffer = buffer;this.exchanger = exchanger;}@Overridepublic void run() {int cycle = 1;for(int i = 0; i < 10; i++) {System.out.printf("Producer: Cycle %d\n",cycle);for (int j=0; j<10; j++){String message="Event "+((i*10)+j);System.out.printf("Producer: %s\n",message);buffer.add(message);}try {buffer = exchanger.exchange(buffer);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("Producer: "+buffer.size());cycle++;}}}
    
   
  
 

package com.bird.concursey.charpet5;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Exchanger;public class Consumer implements Runnable {private List
 
   buffer;private Exchanger
  
   > exchange;public Consumer(List
   
     buffer, Exchanger
    
     > exchange) {super();this.buffer = buffer;this.exchange = exchange;}@Overridepublic void run() {int cycle = 1;for(int i = 0; i < 10; i++) {System.out.printf("Consumer: Cycle %d\n",cycle);try {buffer = exchange.exchange(buffer);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Consumer: "+buffer.size());for (int j=0; j<10; j++){String message=buffer.get(0);System.out.println("Consumer: "+message);buffer.remove(0);}cycle++;}}public static void main(String[] args) {List
     
       buffer1 = new ArrayList
      
       ();List
       
         buffer2 = new ArrayList
        
         ();Exchanger
         
          > exchange = new Exchanger
          
           >();Producer producer = new Producer(buffer1, exchange);Consumer consumer = new Consumer(buffer2, exchange);Thread threadProducer=new Thread(producer);Thread threadConsumer=new Thread(consumer);threadProducer.start();threadConsumer.start();}}
          
         
        
       
      
     
    
   
  
 

The consumer begins with an empty buffer and calls Exchanger to synchronize with theproducer. It needs data to consume. The producer begins its execution with an empty buffer.It creates 10 strings, stores it in the buffer, and uses the exchanger to synchronize withthe consumer.
At this point, both threads (producer and consumer) are in Exchanger and it changes thedata structures, so when the consumer returns from the exchange() method, it will have abuffer with 10 strings. When the producer returns from the exchange() method, it will havean empty buffer to fill again. This operation will be repeated 10 times.
If you execute the example, you will see how producer and consumer do their jobsconcurrently and how the two objects interchange their buffers in every step. As it occurs withother synchronization utilities, the first thread that calls the exchange() method was put tosleep until the other threads arrived.


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.