CodesJava

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.

Example

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 = this.exchanger.exchange(this.object);
            System.out.println(
                    Thread.currentThread().getName() +
                    " exchanged " + previous + " for " + this.object
            );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output

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








Copyright © 2019 CodesJava DMCA.com Protection Status