Thread Java 30 days- day 7 (Exchanger)

paul chou
1 min readAug 13, 2023

The Exchanger class in Java is used to facilitate data exchange between two or more threads. It provides a synchronization point where threads can meet and exchange data.

In each thread, call the exchange() method of the Exchanger instance to exchange data. This method will block until another thread also calls exchange(). When both threads have reached this point, they will exchange their data and continue executing.

import java.util.concurrent.Exchanger;

public class ThreadExchangeExample {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();

Thread thread1 = new Thread(() -> {
try {
String data1 = "Hello from Thread 1";
System.out.println("Thread 1 sending: " + data1);
Thread.sleep(1000); // Simulating some processing
String receivedData = exchanger.exchange(data1);
System.out.println("Thread 1 received: " + receivedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Thread thread2 = new Thread(() -> {
try {
String data2 = "Hello from Thread 2";
System.out.println("Thread 2 sending: " + data2);
Thread.sleep(1500); // Simulating some processing
String receivedData = exchanger.exchange(data2);
System.out.println("Thread 2 received: " + receivedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Thread thread3 = new Thread(() -> {
try {
String data3 = "Hello from Thread 3";
System.out.println("Thread 3 sending: " + data3);
Thread.sleep(2000); // Simulating some processing
String receivedData = exchanger.exchange(data3);
System.out.println("Thread 3 received: " + receivedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
});

thread1.start();
thread2.start();
thread3.start();
}
}

//the answer could be like this:
//Thread 2 sending:Thread 2
//Thread 2 sending:Thread 1
//Thread 3 sending:Thread 3
//Thread 2 received:Thread 1
//Thread 1 received:Thread 2

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response