In this Q&A, we'll go over how to send and receive data between two threads in Java.
Data can be exchanged between two threads via SynchronousQueue. Two queues can be setup to send and receive data from another thread.
In addition to that, Java provides Exchanger class to exchange data. Exchanger is a synchronization point where two threads can exchange same type of data - thread T1 sends object O1 to T2 and receives object O2 from T2.
See demo code below
package com.javahowdoi.thread;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExchangerDemo {
private static class ExchangerTask implements Runnable {
Exchanger<Double> ei;
ExchangerTask(Exchanger<Double> ei ) {
this.ei = ei;
}
@Override
public void run() {
try {
Double i = Math.random();
System.out.println(Thread.currentThread().getName() + " sending # " + i.toString());
i = ei.exchange(i);
System.out.println(Thread.currentThread().getName() + " received # " + i.toString());
}
catch(InterruptedException ie) {
}
}
}
public static void main(String[] args ) {
Exchanger<Double> ei = new Exchanger<>();
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(new ExchangerTask(ei));
es.submit(new ExchangerTask(ei));
es.shutdown();
}
}
Comments
Post a Comment