Multithreading in Java

362
-
Like this post? Rate it:

Ever think of focusing your attention on performing on a single task at a time and do it well? This is usually difficult as human nature is bound to perform multiple tasks at a time. Look around and you will observe that the human body performs a variety of task in parallel or you can say concurrently.

In a similar fashion, computers can also perform operations in concurrent manners. You can get the idea from the example that it is possible to send a file to a printer and receive an email over the same network concurrently. Those computers which have multiple processes can truly execute instructions concurrently.

Concurrency in Java

Java enables concurrency through the language itself and APIs. A typical Java program can have multiple threads of execution, where each thread has its own method call, allowing the process to execute concurrently with other threads while sharing with them application-wide resources such as memory. This capability is called multi-threading.

Uses of Concurrent Programming

There are many applications where concurrent programming is used. For example: when we download a large audio file or video file or a movie over the internet, one may not wait until the entire file downloads before starting the playback. To manage this problem, multiple threads are used, one to download the file and the other one to play the file. Both of these activities proceed concurrently. To avoid inconsistency in playback, threads are synchronized so that player thread doesn’t begin until there is sufficient amount of data is available in the memory to keep the thread (player) busy.

Concurrent Programming is Difficult:

To write multithreaded programs is a tricky process. As discussed, a human can perform functions concurrently but find it difficult to jump between parallel trains of thought. To understand, perform a little experiment: Open four books to introduction page i.e. the first page and try reading them concurrently. Read one paragraph from the first book, then one from the other books, one by one and then loop back to read the next paragraph from the first book to the fourth book. After this experiment, you will appreciate multithreading, switching from one book to the second and so on, reading the paragraph and understand, remembering the place in each of the book, moving the books closer which you are reading and pushing away the others which you are not reading, in all the chaos you are trying to comprehend the content of the books.

Introduction to Multithreading in Java

Java is one of the most commonly used and mature programming languages in the world of software development. Over the years like every programming language Java has evolved and now it has three different platforms and each addresses certain programming requirements.

Java is a multithreaded programming language. A multithread program is such a program which contains two or more parts that can run concurrently and each part or thread can handle different task to perform at the same time. A thread is a line of execution and the smallest piece of code that is dispatched by the scheduler. This independent part of a program is designed in such a way that each part is independent of the other part, and if any exception occurs it doesn’t affect other parts (thread).

What is Multithreading in Java?

Multithreading is a way to allow a program or a process to execute many tasks simultaneously by making optimal use of available resources especially when system has multiple CPU’s.

Advantages of multithreading in Java:

  • It saves CPU’s waiting time
  • Increase the efficiency of CPU’s
  • For user input, multithreading create a separate thread for this task
  • It helps in multitasking by subdividing operations within a single application into individual threads

Lifecycle of a Thread:

A thread follows a particular lifecycle which starts from the initiation/creation stage then move on to run and then finally it dies or destroyed. All these states are illustrated in the UML diagram as follows:

  • New: This is the initiation phase when thread is created. Thread will reside in this state until the run method is not called off. It is also known as born thread.
  • Runnable: After the thread is created and once it starts using start () method then we call that state runnable with the usage of run () method. Thread in this state is considered to be executing its specific task.
  • Waiting: Sometimes a thread transition to the waiting state while it waits for another thread to perform a task. A waiting thread transitions back to the runnable state only when another thread notifies it to continue executing.
  • Timed Waiting: When a thread is in the runnable state it can enter in the timed waiting state for a specific time interval. A thread in this state goes back to the runnable state when the time interval expires or when the event for which it is waiting to occur.
  • Terminated: A running method ends it life when it completes its task. It happens by default.

Java Thread Methods:

  • start (): This method starts the thread in a separate path of execution and then invokes run () method.
  • run (): When thread object starts, then it is made runnable by run () method.
  • suspend (): This method suspends the thread object.
  • sleep (): This method postpone the execution of the thread for a specified time interval, usually in milliseconds.
  • resume (): This method restarts the suspended thread.
  • stop (): This method used to stop the execution of thread before run () method terminates.

Priorities in Java Threads:

In Java, when we create threads instance they will have the same priority, which the processor will schedule without any specific order. It is important that we prioritize the threads. Important threads should always be given high priority as compared to less important threads. Most importantly, those threads which need to run quietly may only need the lowest priority. Priority can be controlled using the Java API’s. For this purpose we use Thread.setPriority () method.

Priority values are as follow:

  • MIN_PRIORITY = 1
  • NORM_PRIORITY = 5
  • MAX_PRIORITY = 10

Keep in mind that priority range of the threads should be in the range between minimum and maximum number.

Create a Thread in Java

Threads are Java language objects and can be created by using two different mechanisms.

1. Extending The Thread Class

In this method, we create a thread by defining a class that is derived from a thread. The run () method will override and contains the code that will be executed by a new thread. This method will be public with a void return type and should not take any arguments.

Actual Code:

Output:

Another Example:

The run () method contains the code that is executed inside the new thread. Once a thread is created one can start it by calling start () method.

Output:

In the above code as you can see Thread.currentThread () is used which returns a reference to that particular thread that is currently executing. While getName () method is being used to point out the current thread.

2. Implementing Runnable Interface

This is one of the easiest ways to create a thread. The runnable interface only contains one method i.e. run () method which will be included in the class during implementation.

Actual Code:

Output:

Another Example:

Output:

In the above piece of code, an instance of the class is created that implements Runnable interface and then passes that particular instance to Thread (Runnable target) constructor.

Simply, a thread can be defined by extending the java.lang.Thread class or by implementing the java.lang.Runnable interface.

Thread vs Runnable: Which one to use?

In case of thread method, where we have to extend from the Thread class is very limited due to the fact that once we extend our class from Thread, you cannot extend anymore from any other class as Java doesn’t support multiple inheritances. If we follow good coding practices then inheritance is meant for extending the parent class functionality to the child class, but in case of thread, once they are created, one cannot extend the functionality of thread class, we just provide the implementation of run () method.

It is recommended that developers should use Runnable object to create threads. This is much flexible method and allows your class to extend from any other class.

RSS
No comments yet. Be the first to add a comment!
Loading...