Share data between two threads in Java
Sharing data between threads in Java can be done through various mechanisms, such as using shared objects, volatile variables, synchronized blocks, locks, or concurrent data structures. Each of these methods has its own advantages and use cases, depending on the specific requirements of the application.
One commonly used approach is using synchronized blocks or methods to ensure that only one thread can access the shared data at a time. This prevents race conditions and ensures data consistency. Another approach is using concurrent data structures like ConcurrentHashMap or ConcurrentLinkedQueue, which provide thread-safe access to their elements without the need for explicit synchronization.

Table of Contents
Let's illustrate how to share data between two threads using synchronized blocks in Java:
java
public class DataSharingExample {
private int sharedData;
public synchronized void setData(int data) {
this.sharedData = data;
}
public synchronized int getData() {
return this.sharedData;
}
public static void main(String[] args) {
DataSharingExample sharedObject = new DataSharingExample();
Thread thread1 = new Thread(() -> {
sharedObject.setData(10);
});
Thread thread2 = new Thread(() -> {
int data = sharedObject.getData();
System.out.println("Thread 2: Data retrieved = " + data);
});
thread1.start();
thread2.start();
}
}
In this example, we have a class DataSharingExample with a shared data field sharedData. We use synchronized methods setData() and getData() to set and retrieve the shared data, ensuring that only one thread can access these methods at a time. In the main() method, we create two threads: one to set the data and another to retrieve it. The use of synchronized methods ensures that the shared data is accessed safely by both threads.