
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do threads communicate with each other in Java?
Inter-thread communication involves the communication of threads with each other. The three methods that are used to implement inter-thread communication in Java
wait()
This method causes the current thread to release the lock. This is done until a specific amount of time has passed or another thread calls the notify() or notifyAll() method for this object.
notify()
This method wakes a single thread out of multiple threads on the current object’s monitor. The choice of thread is arbitrary.
notifyAll()
This method wakes up all the threads that are on the current object’s monitor.
Example
class BankClient { int balAmount = 5000; synchronized void withdrawMoney(int amount) { System.out.println("Withdrawing money"); balAmount -= amount; System.out.println("The balance amount is: " + balAmount); } synchronized void depositMoney(int amount) { System.out.println("Depositing money"); balAmount += amount; System.out.println("The balance amount is: " + balAmount); notify(); } } public class ThreadCommunicationTest { public static void main(String args[]) { final BankClient client = new BankClient(); new Thread() { public void run() { client.withdrawMoney(3000); } }.start(); new Thread() { public void run() { client.depositMoney(2000); } }.start(); } }
Output
Withdrawing money The balance amount is: 2000 Depositing money The balance amount is: 4000
- Related Questions & Answers
- Joining Threads in Java
- Killing threads in Java
- Difference Between Daemon Threads and User Threads In Java
- Place K-knights such that they do not attack each other in C++
- How to implement Concurrency with Threads in Python?
- Minimum and Maximum Priority Threads in Java
- How to create a child window and communicate with parents in Tkinter?
- User-level threads and Kernel-level threads
- Threads in C#
- How to place two divs next to each other in HTML?
- How to destroy threads in C#?
- Java String Concatenation with Other Data Types.
- How to communicate from SAP to Message queue?
- How to draw ellipses on top of each other in HTML5 SVG?
- How can I put two buttons next to each other in Tkinter?
Advertisements