Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Multithreading in Java Explained [With Examples]

Updated on 23 November, 2022

6.38K+ views
9 min read

Threads in Java

Threads in Java assist the efficient operation of a program. The two basic units of execution of proforma are the process and the threads. A process might be an application, Program, or self-Contained execution environment. 

Whereas threads share a resource to that of the process and exist with it. At least one thread is present in every java application called the main thread. Multiple threads can be created from the main thread. Learn more about how to create a thread in Java.

Benefits of Java Thread

  • Less time and resources are required to create a thread compared to processes. Therefore threads are also called a lightweight process.
  • Parent process data and code are shared by the threads. 
  • Intercommunication between threads is easy compared to intercommunication in a process. 
  • Threads in Java can be created through the implementation of the java.lang. Runnable Interface. 

Single thread

Several processing units are present in a program of which the smallest one is referred to as the single thread. Through the use of “thread class” Java applies the threads. Two types of thread exist; the daemon thread and the user thread. 

When the application is to be cleaned, the use of daemon thread occurs. It runs in the background of an application. While the user threads are created when the application first begins.

Advantages of single thread:

  • The application overhead is reduced as the execution of a single thread occurs in a system.
  • The application’s maintenance cost is reduced with the use of single threads.

Multitasking in Java

Multitasking refers to the process of execution of multiple tasks by the CPU at a single time. Sometimes CPU switching might be carried out between tasks by the user to collaborate with each program together. Separate memory and resources are allocated to the processes in multitasking. In two ways, multitasking can be achieved.

1. Multiprocessing (process-based multitasking)

  • A separate memory area is allocated for each process. Therefore there is an address for each process in memory.
  • The processes are heavyweight.
  • There is a high communication cost between processes.
  • Some time is required for switching between the processes. This is required for updating lists, memory maps, etc.

2. Multithreading (thread-based multitasking)

  • The same address is shared between the threads.
  • Threads are lightweight.
  • There is a low communication cost between the threads.

What is Multithreading?

When two or more threads execute in a program concurrently, the mechanism is referred to as multithreading.  A single process creates many threads increasing the computation power. Two or more parts of a program are executed in a way that leads to the maximum utilization of the CPU.

Threads are referred to as the individual parts of the program. The processes in an application can contain either multiple threads or single threads.
Multiple threads of an application are allowed by the Java Virtual Machine. Every thread has its own priority. Therefore, preference of execution is given to the threads having a higher priority than those having a lower priority. 

To achieve multitasking, both the process of multithreading and multiprocessing is used. Because a shared memory area is used in multithreading, it is mostly used over multiprocessing. Memory is saved as extra allocation of memory is not required. Further, the time taken is lesser than the multiprocessing as context-switching occurs between threads.

In animation, games, Java multithreading is used. Click if you want to learn more about Java architecture and components.

Two Mechanisms can be used for creating threads.

1. Thread class extension

2. Runnable Interface implementation

Thread Class vs Runnable Interface

  • Extending the “Thread class’ cannot extend other classes as multiple inheritances is not supported in Java. But with the implementation of the interface “Runnable”, other base classes can be extended from the class.
  • A thread’s basic functionality can be extended through extending the Thread class as inbuilt methods are provided such as interrupt(), yield(), etc.
  • AN object that multiple threads can share will be provided when runnable is used.

Java Thread class

Thread programming in Java is achieved through the thread class. Constructors are provided by the thread class and methods for performing thread operations. A thread class implements a runnable interface and extends Object class.

A few common thread methods used are:

  1. start():  The thread execution is started by this method. The run() method is called upon by the JVM.
  2. sleep(int milliseconds): Execution of the thread is paused for milliseconds that is provided as the threading process is made to sleep through this method. After the pause, the execution of the thread begins again. Threads are able to be synchronized through this method.
  3. getName(): The thread name is returned through this method.
  4. setPriority(int new priority): The thread priority is changed through this method.
  5. yield (): The current thread is made to halt with the execution of the other threads by this method.
  6. run(): The method is for starting an action in the thread.
  7. getPriority(): The thread priority is returned through the use of this method.
  8. setName(): The thread name is changed through this method.
  9. getId(): The thread id is returned through this method.
  10. suspend(): The thread is suspended through this method.

Thread life cycle

The thread life cycle has various stages, which are listed below:

  1. New: “Thread class” is used for creating a thread in this stage. Until the thread is started, the program stays in this stage. The method is also called the born thread.
  2. Runnable: The start method invokes the thread instance at this stage of the thread lifecycle. The scheduler is handed over with the control of the thread for finishing the execution. Whether the thread should be executed or not depends upon the scheduler.
  3. Running: Once the execution of the thread is started, the stage is shifted to the “running” stage. One thread is selected by the scheduler from the pool of threads and starts the execution of the application.
  4. Waiting: As the name suggests, in this phase of the lifecycle the thread waits. Thread synchronization is essential due to the running of multiple threads in an application. Therefore, there is a necessity for a thread to wait, until the execution of the other thread gets over. Therefore, the stage of the lifecycle is also known as the waiting stage.
  5. Dead: The stage where the termination of the thread occurs is termed as the “dead” stage. Once the thread gets transferred from the running to the end of processing, it gets terminated and hence is in the “dead state”

Thread Synchronization in Java

Asynchronous behaviour occurs in a program in the case of multithreading. If supposedly data is written through one thread and the reading of the data is carried out by another thread simultaneously, inconsistency might be created in the application.

The resources that are shared between threads need to be accessed by other threads. Therefore in such cases, the approach of synchronization is approached. Synchronized methods are available in Java to achieve synchronization behaviour. 

When a thread reaches the synchronized block, then once it reaches, the method cannot be called by other threads on the same object. Until the thread finishes executing the block and exits from it, the other threads have to halt and wait.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Advantages of Multithreading

  • Multiple operations can be performed at the same time. With the independent threads running, the user is not blocked.
  • Time is saved as multiple operations run together.
  • A thread cannot be affected by another thread as they are independent. The occurrence of an exception in one thread doesn’t affect the execution of other threads.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Example of multithreading

An example of a multithreading program in java has been shown below:

Figure 1: A snippet of the multithreading code example

The code explanation

Line 3: The class “GuruThread1” implements runnable.

Line 8: It displays the class main method.

Line 9: The thread class is instantiated and an instance “guruThread1″ is created and a thread is created.

Line 10: The “Thread class” is instantiated and an instance “guruThread2” and a thread is created.

Line 11: The thread named guruThread1 is started.

Line 12: The thread named guruThread2 is started.

Line 13: The text “Thread names are following:” is outputted.

Line 14: The method getName() is used to get the thread1 name.

Line 15: The method getName() is used to get the thread2 name.

Execution of the above code results in the following output: 

Figure: A screenshot of the output generated from the multithreading program in Java (taken from 

Conclusion

The article discussed the concept of multithreading in Java along with an example of a multithreading program in java. Your learning doesn’t stop here and get along with all the other foundation concepts of Java. 

If you are interested in mastering your programming skills at a friendly price and make yourself industry-ready, you can check the course offered by upGrad “Master of Science in Computer Science”. It is for all mid-level professionals within the age group of 21 to 45 years of age. The course is certified by Liverpool John Moores University, and designed with 500+ hours of learning, 309 projects, and assignments to bring the best out of you. If you have any queries drop us a message, our team will contact you.

Frequently Asked Questions (FAQs)

1. What is the difference between Multithreading and Multiprocessing?

CPUs are added to increase computational power in multiprocessing, while multithreading divides a single process into several threads to increase processing capacity. Multiprocessing allows for the execution of several processes at the same time. Multithreading, on the other hand, executes many threads of a process at the same time. Multiprocessing is divided into two types: symmetric and asymmetric, whereas multithreading is not categorised. Operation creation in multiprocessing is a time-consuming process, but process creation in multithreading is done in a cost-effective manner. Finally, in multiprocessing, each process has its own address space, but in multithreading, all threads share a single address space.

2. What are the disadvantages of Multithreading?

Multiple threads can execute separately while using the same process resources because of multithreading, a CPU feature. A thread is a set of instructions that may or may not execute in the same parent process like other threads. Multithreading has a number of drawbacks in the operating system. To begin with, multithreading requires more rigorous synchronisation in order to perform effectively. It can take up a lot of storage space for stalled threads and requires extra thread or process support. If a parent process requires many threads to function properly, the child processes should be multithreaded as well. Finally, multithreading adds cost to context switching

3. Where is Java used in real life?

Because of its remarkable capabilities, Java has become the most efficient programming language. From a corporate e-commerce website to android applications, from research areas to financial services like electronic trading systems, from games like Minecraft to desktop programmes, Java is utilised in many areas in the real world. Many organisations utilise Java to write front and back office electronic trading systems, settlement and confirmation systems, data processing projects, and other projects in the financial services industry. Java is also popular in the worlds of e-commerce and online applications. Java is used to write and build a lot of valuable software and development tools.

RELATED PROGRAMS