Java Multithreading
Java Multithreading is a concept, which explains how to run multiple threads simultaneously under a single process. First lets examine what is a thread then we can move on to the multithreading concept in Java.
What is a Thread
Java thread is a light weight process which runs within in a Java application/process. In more specifically, java thread is a sub-process with in the process and helps to performs the desired tasks to run parallel along with other threads.
Running multiple threads in a application helps to improve the performance of the application and also helps to use the CPU usage better.

Advantages and disadvantages of Multithreading in Java
# | Advantages | Disadvantages |
---|---|---|
1 | We can execute multiple tasks of an application at a time | Thread synchronization is an extra over head to the developers |
2 | Reduces the complexity of a big applications | Shares the common data across the threads might cause the data inconsistency or thread sync issues |
3 | Helps to improve the performance of an application drastically | Threads blocking for resources is more common problem |
4 | Utilizes the max resources of multiprocessor systems | Difficult in managing the code in terms of debugging or writing the code |
5 | Better user interface in case of GUI based applications | |
6 | Reduces the development time of an application | |
7 | All the threads are independent , any unexpected exception happens in any of the thread will not lead to an application exit. |
If you have to build a simple chat application(consider only two users without any server and User Interface).
The requirement is that, while sending the messages to other user have to receive the messages at same time.
If we write a program with one thread(i.e., main thread), can't receive the messages while user is sending the messages or can't send the messages while receiving the messages.
Consider below statements
while(true) { receivemessages(); sendmessages(); }
If we see above code, we can't send the messages while receiving it and can't receive the messages while sending it.
To send and receive both at the same time needed two applications, one for receiving and another for sending.
Two users its fine what about multiple users practically its impossible to have those many applications :).
To overcome the above problem we have a solution that is nothing but a thread.
One thread will be sending it and other thread will be receiving it.
The above code will becomes like the following.
Sender threadwhile(true) { sendmessages(); }Receiver thread
while(true) { receivemessages (); }