Java Multithreading

Java program support Multithreading internally, by default all programs of java execute as a thread. A multithreaded program may contains more than one part that can run concurrently and each part is known as thread.

  • Java supports thread based Multitasking.
  • Multithreading is a specialized form of Multitasking.
  • Multithreading enables to write efficient program that make maximum use of CPU, because idle time is kept minimum.

Programs written without multithreading run as a single thread, causing problems when multiple events or actions need to occur at the same time. Multithreading is used when you want your program to perform multiple task concurrently.


Process vs Thread:

  • Both process and Thread are independent path of execution but one process can have multiple Threads.
  • Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and share it with other threads.
  • Threads are also refereed as task or light weight process.
  • Threads from same process can communicate with each other by using keyword like wait and notify and much simpler than inter process communication.
  • Another difference between Process and Thread is that it's How Thread and process are created. It's easy to create Thread as compared to Process which requires duplication of parent process.
  • All Threads which is part of same process share system resource like file descriptors , Heap Memory and other resource but each Thread has its own Exception handler and own stack.
  • Every thread in Java is created and controlled by a unique object of the java.lang.Thread class.

Difference between Multitasking and Multithreading

Multitasking
Multithreading
In Multitasking operating system tasks are know as heavy-weight process. In Multithreading environment tasks are light weight process or threads.
Multitasking process takes a seperate address space. These are the different programs run on a single system. Threads on other hand share the same address space and co-operatively share the same heavy weight process.
Inter-process communication is expensive and limited. Inter-thread communication is very light-weight and pervasive.
Context switching, changing the running process, is also heavy-weight. Context switching is fast and an integral part of running any one program.