Programs

Multithreading in Java Explained [With Examples]

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.

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.

Example of multithreading

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

Source

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: 

Source

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.

Land on Your Dream Job

Enrol for Master of Computer Science with upGrad
Apply Now

0 replies on “Multithreading in Java Explained [With Examples]”

Accelerate Your Career with upGrad

Our Popular Software Engineering Courses

×