Easy learning with example program codes

exchanger in java

The java.util.concurrent.Exchanger Class provides a sort of rendezvous point for two threads. At this point the two threads can exchange their respective Objects with the each other.


import java.util.concurrent.Exchanger;
public class ExchangerTest {
    public static void main(String args[]) throws InterruptedException {
    	Exchanger exchanger = new Exchanger();
    	ExchangerRunnable exchangerRunnable1 =
    	        new ExchangerRunnable(exchanger, "Object A");
    	ExchangerRunnable exchangerRunnable2 =
    	        new ExchangerRunnable(exchanger, "Object B");
    	new Thread(exchangerRunnable1).start();
    	new Thread(exchangerRunnable2).start();
class ExchangerRunnable implements Runnable{
    Exchanger exchanger = null;
    Object    object    = null;
    public ExchangerRunnable(Exchanger exchanger, Object object) {
        this.exchanger = exchanger;
        this.object = object;
    public void run() {
        try {
            Object previous = this.object;
            this.object =;
                    Thread.currentThread().getName() +
                    " exchanged " + previous + " for " + this.object
        } catch (InterruptedException e) {


Thread-1 exchanged Object B for Object A
Thread-0 exchanged Object A for Object B
Please follow and like us:

Copyright © 2020 CodesJava Protection Status