Middle — Middle+
How can data transfer be implemented using streams?
sobes.tech AI
Answer from AI
Data transfer between threads in Java can be implemented in several ways:
-
Shared objects with synchronization — threads work with a shared object, access to which is controlled using
synchronized,wait(), andnotify(). -
Using thread-safe collections from
java.util.concurrent, such asBlockingQueue. -
Using classes from
java.util.concurrent, such asExchanger,SynchronousQueue, etc.
Example with BlockingQueue:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
Thread producer = new Thread(() -> {
try {
queue.put("Data");
System.out.println("Producer put data");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
String data = queue.take();
System.out.println("Consumer received: " + data);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
}
}
In this example, one thread puts data into the queue, and another retrieves it, with BlockingQueue ensuring thread safety and blocking the thread if the queue is empty or full.