Multithreading
The java programming language allows us to create a program that contains one or
more parts that can run simultaneously at the same time. This type of program is
known as a multithreading program. Each part of this program is called a thread.
Every thread defines a separate path of execution in java. A thread is explained in
different ways, and a few of them are as specified below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, multiple threads can run at a time, which enables the java to write
multitasking programs. The multithreading is a specialized form of multitasking.
All modern operating systems support multitasking. There are two types of
multitasking, and they are as follows.
Process-based multitasking
Thread-based multitasking
It is important to know the difference between process-based and thread-based
multitasking. Let's distinguish both.
Process-based multitasking Thread-based multitasking
It allows the computer to run two or It allows the computer to run two or
more programs concurrently more threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process is a larger unit. Thread is a part of process.
Process is heavy weight. Thread is light weight.
Process requires seperate address space Threads share same address space.
for each.
Process never gain access over idle time Thread gain access over idle time of
of CPU. CPU.
Inter process communication is Inter thread communication is not
expensive. expensive.
Life cycle of thread
The java programming language allows us to create a program that contains one or
more parts that can run simultaneously at the same time. This type of program is
known as a multithreading program. Each part of this program is called a thread.
Every thread defines a separate path of execution in java. A thread is explained in
different ways, and a few of them are as specified below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, a thread goes through different states throughout its execution. These
stages are called thread life cycle states or phases. A thread may in any of the states
like new, ready or runnable, running, blocked or wait, and dead or terminated state.
The life cycle of a thread in java is shown in the following figure.
Let's look at each phase indetailed.
New
When a thread object is created using new, then the thread is said to be in the New
state. This state is also known as Born state.
Example
Thread t1 = new Thread();
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable
state. This state is also known as a Ready state.
Example
[Link]( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( )
method of a thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various
reasons like sleep( ) method called, wait( ) method called, suspend( ) method
called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state
due to reasons like sleep time completed, waiting time completed, notify( ) or
notifyAll( ) method called, resume( ) method called, etc.
Example
[Link](1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its
execution completed or the stop( ) method called. The dead state is also known as
the terminated state.
Creating threads in java
In java, a thread is a lightweight process. Every java program executes by a thread
called the main thread. When a java program gets executed, the main thread
created automatically. All other threads called from the main thread.
The java programming language provides two methods to create threads, and they
are listed below.
Using Thread class (by extending Thread class)
Uisng Runnable interface (by implementing Runnable interface)
Let's see how to create threads using each of the above.
Extending Thread class
The java contains a built-in class Thread inside the [Link] package. The Thread
class contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
Step-1: Create a class as a child of Thread class. That means, create a class
that extends Thread class.
Step-2: Override the run( ) method with the code that is to be executed by
the thread. The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
Look at the following example program.
When we run this code, it produce the following output.
Implementng Runnable interface
The java contains a built-in interface Runnable inside the [Link] package. The
Runnable interface implemented by the Thread class that contains all the methods
that are related to the threads.
To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Step-2: Override the run( ) method with the code that is to be executed by
the thread. The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as
parameter to the Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the
above step.
Look at the following example program.
When we run this code, it produce the following output.
Java Thread Priority
In a java programming language, every thread has a property called priority. Most
of the scheduling algorithms use the thread priority to schedule the execution
sequence. In java, the thread priority range from 1 to 10. Priority 1 is considered as
the lowest priority, and priority 10 is considered as the highest priority. The thread
with more priority allocates the processor first.
The java programming language Thread class provides two
methods setPriority(int), and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread
priority, and they are listed below.
MAX_PRIORITY - It has the value 10 and indicates highest priority.
NORM_PRIORITY - It has the value 5 and indicates normal priority.
MIN_PRIORITY - It has the value 1 and indicates lowest priority.
🔔 The default priority of any thread is 5 (i.e. NORM_PRIORITY).
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It
takes an integer range from 1 to 10 as an argument and returns nothing (void).
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It
does not takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
When we run this code, it produce the following output.
Java Thread Synchronisation
The java programming language supports multithreading. The problem of shared
resources occurs when two or more threads get execute at the same time. In such a
situation, we need some way to ensure that the shared resource will be accessed by
only one thread at a time, and this is performed by using the concept called
synchronization.
🔔 The synchronization is the process of allowing only one thread to access a
shared resource at a time.
In java, the synchronization is achieved using the following concepts.
Mutual Exclusion
Inter thread communication
In this tutorial, we discuss mutual exclusion only, and the interthread
communication will be discussed in the next tutorial.
Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one
another while they accessing the shared resource. In java, mutual exclusion is
achieved using the following concepts.
Synchronized method
When a method created using a synchronized keyword, it allows only one object to
access it at a time. When an object calls a synchronized method, it put a lock on
that method so that other objects or thread that are trying to call the same method
must wait, until the lock is released. Once the lock is released on the shared
resource, one of the threads among the waiting threads will be allocated to the
shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and
other threads (thread-2, thread-3, and thread-4) are waiting for the resource
(synchronized method). When thread-1 completes it task, then one of the threads
that are waiting is allocated with the synchronized method, in the above it is
thread-3.
When we run this code, it produce the following output.