A Thread is a
1.Light Weight Process.
2.Flow of execution.
3.a Task which runs along with other Tasks.
A Process under execution has below segments in memory Code, Data, Stack, Heap.
But a thread may have only Stack or Heap, and other segments are shared with the Main thread.
As already said, Thread is a separate flow of execution. Multiple Threads are required in a program to perform multiple tasks simultaneously.
Actually, CPU executes only one Thread at a time. But CPU switches between different Threads of a Process, hence we feel that multiple threads are executed simultaneously.
One more advantages of Thread over Process is, Threads use CPU more effectively, compared to Processes.
For example, consider a Video Player Application, it may need multiple threads as below tasks need to run simultaneously.
1.To download and buffer video packets.
2.To play(or render) Video pixels on screen.
3.To play audio.
Each above Task may need a separate Thread. These threads run simultaneously, and User feels that these tasks parallely.
Java has built in support for Multi threading.
In Java there are two ways to create and start a new Thread.
1.By extending from java.lang.Thread class
2.By implementing java.lang.Runnable interface
Below are steps involved to create and start Thread, using Thread class
1.Write a class which extends from Thread class.
2.Override public void run() method in class created above.
3.Write business logic which need to be executed in new thread, in run() method of step2.
4.In main method Create an object of Class of Step1
5.With the object, invoke start() method