The use of a Java multi thread programming Exchanger data exchange instances

  • 2020-04-01 03:50:38
  • OfStack

It is used to realize the data exchange between two people. Each person wants to exchange data with the other after completing a certain transaction. The first person who takes out the data first will wait for the second person to come with the data before exchanging the data with each other.


package com.ljq.test.thread;
 
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class ExchangerTest {
 
    public static void main(String[] args) {
        
        ExecutorService service = Executors.newCachedThreadPool();
        final Exchanger exchanger = new Exchanger();
        service.execute(new Runnable(){
            public void run() {
                try {             
 
                    String data1 = " Zhang SAN ";
                    System.out.println(" thread " + Thread.currentThread().getName() + " In the process of transferring data '" + data1 +"' In go out ");
                    Thread.sleep((long)(Math.random()*10000));
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println(" thread " + Thread.currentThread().getName() + " The returned data is '" + data2+"'");
                }catch(Exception e){
                    
                }
            } 
        });
        service.execute(new Runnable(){
            public void run() {
                try {             
                    String data1 = " Li si ";
                    System.out.println(" thread " + Thread.currentThread().getName() + " In the process of transferring data '" + data1 +"' In go out ");
                    Thread.sleep((long)(Math.random()*10000));                
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println(" thread " + Thread.currentThread().getName() + " The returned data is '" + data2 + "'");
                }catch(Exception e){
                    
                }             
            } 
        });   
    }
}

Return result:


thread pool-1-thread-1 In the process of transferring data ' Zhang SAN ' In go out
thread pool-1-thread-2 In the process of transferring data ' Li si ' In go out
thread pool-1-thread-1 The returned data is ' Li si '
thread pool-1-thread-2 The returned data is ' Zhang SAN '


Related articles: