The Java concurrency API provides a synchronization utility that allows the interchange of data between two concurrent tasks. In more detail, the Exchanger class allows the definition of a synchronization point between two threads. When the two threads arrive to this point, they interchange a data structure so the data structure of the first thread goes to the second one and the data structure of the second thread goes to the first one.

This class may be very useful in a situation similar to the producer-consumer problem. This is a classic concurrent problem where you have a common buffer of data, one or more producers of data, and one or more consumers of data. As the Exchanger class only synchronizes two threads, you can use it if you have a producer-consumer problem with one producer and one consumer.

In this recipe, you will learn how to use the Exchanger class to solve the producer-consumer problem with one producer and one consumer.

1. First, let's begin by implementing the producer. Create a class named Producer and specify that it implements the Runnable interface.

package com.packtpub.java7.concurrency.chapter3.recipe7.task;

import java.util.List;
import java.util.concurrent.Exchanger; /**
* This class implements the producer
*
*/
public class Producer implements Runnable { /**
* Buffer to save the events produced
*/
private List<String> buffer; /**
* Exchager to synchronize with the consumer
*/
private final Exchanger<List<String>> exchanger; /**
* Constructor of the class. Initializes its attributes
* @param buffer Buffer to save the events produced
* @param exchanger Exchanger to syncrhonize with the consumer
*/
public Producer (List<String> buffer, Exchanger<List<String>> exchanger){
this.buffer=buffer;
this.exchanger=exchanger;
} /**
* Main method of the producer. It produces 100 events. 10 cicles of 10 events.
* After produce 10 events, it uses the exchanger object to synchronize with
* the consumer. The producer sends to the consumer the buffer with ten events and
* receives from the consumer an empty buffer
*/
@Override
public 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 {
/*
* Change the data buffer with the consumer
*/
buffer=exchanger.exchange(buffer);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.printf("Producer: %d\n",buffer.size()); cycle++;
} } }

2. Second, implement the consumer. Create a class named Consumer and specify that it implements the Runnable interface.

package com.packtpub.java7.concurrency.chapter3.recipe7.task;

import java.util.List;
import java.util.concurrent.Exchanger; /**
* This class implements the consumer of the example
*
*/
public class Consumer implements Runnable { /**
* Buffer to save the events produced
*/
private List<String> buffer; /**
* Exchager to synchronize with the consumer
*/
private final Exchanger<List<String>> exchanger; /**
* Constructor of the class. Initializes its attributes
* @param buffer Buffer to save the events produced
* @param exchanger Exchanger to syncrhonize with the consumer
*/
public Consumer(List<String> buffer, Exchanger<List<String>> exchanger){
this.buffer=buffer;
this.exchanger=exchanger;
} /**
* Main method of the producer. It consumes all the events produced by the Producer. After
* processes ten events, it uses the exchanger object to synchronize with
* the producer. It sends to the producer an empty buffer and receives a buffer with ten events
*/
@Override
public void run() {
int cycle=1; for (int i=0; i<10; i++){
System.out.printf("Consumer: Cycle %d\n",cycle); try {
// Wait for the produced data and send the empty buffer to the producer
buffer=exchanger.exchange(buffer);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.printf("Consumer: %d\n",buffer.size()); for (int j=0; j<10; j++){
String message=buffer.get(0);
System.out.printf("Consumer: %s\n",message);
buffer.remove(0);
} cycle++;
} } }

3. Finally, implement the main class of the example by creating a class named Core and add the main() method to it.

package com.packtpub.java7.concurrency.chapter3.recipe7.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger; import com.packtpub.java7.concurrency.chapter3.recipe7.task.Consumer;
import com.packtpub.java7.concurrency.chapter3.recipe7.task.Producer; /**
* Main class of the example
*
*/
public class Main { /**
* Main method of the example
* @param args
*/
public static void main(String[] args) { // Creates two buffers
List<String> buffer1=new ArrayList<>();
List<String> buffer2=new ArrayList<>(); // Creates the exchanger
Exchanger<List<String>> exchanger=new Exchanger<>(); // Creates the producer
Producer producer=new Producer(buffer1, exchanger);
// Creates the consumer
Consumer consumer=new Consumer(buffer2, exchanger); // Creates and starts the threads
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 the producer. 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 with the consumer.

At this point, both threads (producer and consumer) are in Exchanger and it changes the data structures, so when the consumer returns from the exchange() method, it will have a buffer with 10 strings. When the producer returns from the exchange() method, it will have an 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 jobs concurrently and how the two objects interchange their buffers in every step. As it occurs with other synchronization utilities, the first thread that calls the exchange() method was put to sleep until the other threads arrived.

Exchanger, Changing data between concurrent tasks的更多相关文章

  1. 未能从程序集 C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Data.Entity.Build.Tasks.dll 加载任务“EntityClean”

    问题: 未能从程序集 C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Data.Entity.Build.Tasks.dll 加载任务“Entity ...

  2. Fork and Join: Java Can Excel at Painless Parallel Programming Too!---转

    原文地址:http://www.oracle.com/technetwork/articles/java/fork-join-422606.html Multicore processors are ...

  3. java.util.concurrent.Exchanger应用范例与原理浅析--转载

    一.简介   Exchanger是自jdk1.5起开始提供的工具套件,一般用于两个工作线程之间交换数据.在本文中我将采取由浅入深的方式来介绍分析这个工具类.首先我们来看看官方的api文档中的叙述: A ...

  4. java Concurrent包学习笔记(六):Exchanger

    一.概述 Exchanger 是一个用于线程间协作的工具类,Exchanger用于进行线程间的数据交换,它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据.这两个线程通过exchange 方法 ...

  5. 并发编程-concurrent指南-交换机Exchanger

    java.util.concurrent包中的Exchanger类可用于两个线程之间交换信息.可简单地将Exchanger对象理解为一个包含两个格子的容器,通过exchanger方法可以向两个格子中填 ...

  6. Java Concurrency - Concurrent Collections

    Data structures are a basic element in programming. Almost every program uses one or more types of d ...

  7. JUC——线程同步辅助工具类(Exchanger,CompletableFuture)

    Exchanger交换空间 如果现在有两个线程,一个线程负责生产数据,另外一个线程负责消费数据,那么这个两个线程之间一定会存在一个公共的区域,那么这个区域的实现在JUC包之中称为Exchanger. ...

  8. Java并发编程原理与实战二十九:Exchanger

    一.简介 前面三篇博客分别介绍了CyclicBarrier.CountDownLatch.Semaphore,现在介绍并发工具类中的最后一个Exchange.Exchange是最简单的也是最复杂的,简 ...

  9. 并发新构件之Exchanger:交换器

    Exchanger:JDK描述:可以在对中对元素进行配对和交换的线程的同步点.每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象.Exchang ...

随机推荐

  1. leetcode—Palindrome 解题报告

    1.题目描述 Given a string s, partition s such that every substring of the partition is a palindrome. Ret ...

  2. connect to a specific wifi network in Android programmatically

    http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-prog ...

  3. keil编译STM32工程时 #error directive: "Please select first the target STM32F10x device used in your application (in stm32f10x.h file)"

    我们可以双击错误,然后会自动定位到文件 stm32f10x.h 中出错的地方,可以看到代码: #if !defined (STM32F10X_LD) && !defined (STM3 ...

  4. STM32硬件调试详解

    STM32的基本系统主要涉及下面几个部分: 一.电源 1).无论是否使用模拟部分和AD部分,MCU外围出去VCC和GND,VDDA.VSSA.Vref(如果封装有该引脚)都必需要连接,不可悬空: 2) ...

  5. AQTime教程(1)

    AQTime教程 1 简介 AQTime和MemProof都是AutomatedQA旗下的产品,AQTime比MemProof提供了更丰富强大的功能.该产品含有完整的性能和调试工具集,能够收集程序运行 ...

  6. fastica matlab 转载

    FastICA工具箱1 http://chunqiu.blog.ustc.edu.cn/?p=68#comment-3512 FastICA代码网址如下:http://research.ics.aal ...

  7. ECSHOP在线手册布局参考图--登录/注册页 user_passport.dwt

        A.会员登录框 1,设置方法 自带模块 2,代码相关 user_passport.dwt 中 <div class="usBox_1 f_l"> <div ...

  8. Spring ApplicationContextAware获取上下文

    一.ApplicationContextAware 用处 Spring 提供了ApplicationContextAware类,通过它可以获取所有bean上下文. 二.怎么用? ①.定义一个工具类,去 ...

  9. MFC 学习 之 状态栏的添加

    1.首先声明一个 CStatusBar  m_bar;//声明对象2.然后打开视图资源 String Table中添加两个字段值 3.创建了两个字段值以后,在OnintDialog() 所在的 .cp ...

  10. maven配置编译路径

    在build标签下添加 <build> <sourceDirectory>src/main/java</sourceDirectory> <resources ...