Java. Util. Concurrent. Exchanger can be used for data exchange, or called “data exchange”. The two threads can use the SANo3300 to exchange data. The following figure illustrates the use of the SANo3300

In the code below

  • First, we defined a SANoer for data exchange
  • Then two thread objects bookExchanger1 and bookExchanger2 are defined, and both threads hold a Exchanger object for data exchange
  • Each of the two threads has its own data, such as the String[] book array in the code below.
Public static void main(String[] args) {// Data Exchanger - Data <String> recovery = new recovery <>(); / / thread in book 1 BookExchanger bookExchanger1 = new BookExchanger (exchanger, new String [] {" Java from entry to give up ", "Java programming ideas"}); // BookExchanger 2 BookExchanger 2 = new bookExchanger2 (EXCHANGER, new String[]{"C "," Python "}); new Thread(bookExchanger1).start(); new Thread(bookExchanger2).start(); }Copy the code

The BookExchanger is inherited from the Runnable representing the book exchange reader, who is holding a data Exchanger for exchanging books.

public class BookExchanger implements Runnable{ Exchanger<String> exchanger = null; String[] books = null; // Book array public san_recovery (san_recovery <String> san_recovery, String[] books) {this. San_recovery = san_recovery; this.books = books; } @Override public void run() { try { for(String bookName : // Data exchange, bookName is my book, exBook is my book String exBook = this.recovery. Exchange (bookName); // Data exchange, bookName is my book, exBook is my book. System.out.println(thread.currentThread ().getName()) + "; } } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

Execute the code above to get the following printout. You can see that only two threads have completed an exchange before the next exchange can take place.

Thread-1 uses "C language programming" to "Java from the beginning to give up" Thread-1 uses "Actual Python data analysis" to "Java Programming Ideas" Thread0 replaces Java Programming Ideas with Actual Python Data AnalysisCopy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series