Junior — Middle
How do data exchanges and interactions occur between threads in a multithreaded application?
sobes.tech AI
Answer from AI
In a multithreaded Java application, data exchange and interaction between threads occur through shared objects and synchronization mechanisms. The main methods are:
- Shared variables and objects: Threads can read and modify shared data, but synchronization is used to prevent race conditions.
- The
synchronizedkeyword: Allows locking access to a critical section of code so that only one thread can execute it. - Classes from the
java.util.concurrentpackage: For example,Lock,Semaphore,CountDownLatch,CyclicBarrierfor more flexible synchronization. - Interaction through queues: Threads can exchange data via thread-safe queues, such as
BlockingQueue. - Methods
wait(),notify(),notifyAll(): Allow threads to wait for a certain condition and notify each other of changes.
Example of using synchronized and wait/notify:
class SharedResource {
private int data;
private boolean available = false;
public synchronized void produce(int value) throws InterruptedException {
while (available) {
wait();
}
data = value;
available = true;
notify();
}
public synchronized int consume() throws InterruptedException {
while (!available) {
wait();
}
available = false;
notify();
return data;
}
}
Thus, interaction is built on controlling access to shared data and notifying threads about events.