Multithreading Basics

Learn development of multithreading applications


Multithreading allows programmer to execute multiple activities in same process. A thread is separate path of execution. Thread has four attributes associated with them that's why thread is considered lightweight as compared to process.


By default in every java program there is only one thread Main. In a single threaded environment only one task can be executed at a time.
In java every thread is created and controlled by unique object of java.lang.Thread class.


Multiple threads are created in same process, means thread share memory address.



The Main Thread

When java program is executed, a thread to created automatically to execute main method of program. This thread is known as Main thread. This thread terminated when execution of main method is over.


Example for printing name of main thread

// Program to print name of thread
class myThread
{
 public static void main(String arg[])
  {
    System.out.println("Name of Running Thread:"+Thread.currentThread().getName());
  }
}
/* Output
Name of Running Thread:main
*/	

Thread Creation


Why java has two ways to create threads

  • By implementing Runnable interface, programmer has to define only run() method. So if programmer wants to create a simple thread, Runnable is good choice.

  • In java only one class can be extended so if Thread class is used to create thread then other class can't be extended whereas if interface is implemented then programmer can extend any class he wants.