Multithreading in Java

  • A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
  • In a simple word, thread is a lightweight sub-process.
  •  It is a smallest unit of processing.
  • When these threads execute concurrently for accomplishing a task is known multithreading.
  • In multithreading, each thread defines a separate path of execution. 
  • In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
Java Process and Thread Diagram

 In a java programming, Thread is a predefined class within a java.lang package.

Operating system (OS) can contain multiple process, in the above figure, there are three process  P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.  

Difference between Process and Thread

Process Thread
A process has their own virtual address space. Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space. Two threads running within a process uses the same address space.
Every process has its own data segment All threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes. In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead. Threads have almost no overhead;
Process is heavy weight. Threads are light weight process (LWP).
Process contains much information about system, resource. Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process. No duplication of resources is required when we create a child thread from main thread.