Inter thread communication can be defined as the exchange of messages between two or more threads. The transfer of messages takes place before or after the change of state of a thread.
For example, an active thread may notify to another suspended thread just before switching to the suspended state.
In Java, inter-thread communication can be achieved through the use of the wait(), notify() and notifyAll() methods. These methods are part of the Object class, which is the base class for all Java objects.
1. wait(): The wait() method is used to suspend the current thread and wait for a notification from another thread. The thread that calls the wait() method must own the object's monitor. If the thread does not own the monitor, an IllegalMonitorStateException is thrown.
The object class deceleration of wait() method is shown below
final void wait()
2. notify(): The notify() method is used to wake up a single thread that is waiting on the object's monitor. The thread that calls the notify() method must own the object's monitor. If the thread does not own the monitor, an IllegalMonitorStateException is thrown.
The object class deceleration of notify() method is shown below
final void notify()
3. notifyAll(): The notifyAll() method is used to wake up all threads that are waiting on the object's monitor. The thread that calls the notifyAll() method must own the object's monitor. If the thread does not own the monitor, an IllegalMonitorStateException is thrown.
The object class deceleration of notifyAll() method is shown below
final void notifyAll()
To use these methods for inter-thread communication, the following steps should be followed:
- Create a shared object between the threads
- Synchronize the methods that access the shared object
- Use wait(), notify(), and notifyAll() to signal between threads.
Here's an example of how inter-thread communication can be achieved in Java:
public class InterThreadCommunicationExample { public static void main(String[] args) { SharedObject sharedObject = new SharedObject(); Thread thread1 = new Thread(() -> { synchronized (sharedObject) { try { sharedObject.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread 1 notified"); } }); Thread thread2 = new Thread(() -> { synchronized (sharedObject) { System.out.println("Thread 2 sending notification"); sharedObject.notify(); } }); thread1.start(); thread2.start(); } } class SharedObject {}
In this example, the main method creates a shared object (SharedObject). Two threads are created - thread1 and thread2. Thread1 waits for a notification from thread2 by calling the wait() method on the shared object within a synchronized block. Thread2 sends the notification by calling the notify() method on the shared object within a synchronized block. When thread1 receives the notification, it prints "Thread 1 notified" to the console.
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.