Till now we have seen only single thread java programs(i.e., main thread) have you ever imagined that we can run parallel threads to perform the different tasks at a time in Java.
Let's see what is a thread in java, Java thread is a light weight process which runs within in a Java application as an independent process. In more specifically, java thread is a process with in the process and helps to performs the desired tasks parallelly or concurrently.
Let's explain in very simple terms, you have to build a simple chat application(consider only two users without any server and UI).
The requirement is that, while sending the messages to other user have to receive the messages as well.
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.
Lets see the below example:-
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.
We will see in coming chapters about how to create a thread and start a thread.