Unit1_Multithreading
Unit1_Multithreading
• Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process
resources.
• A thread in Java is the direction or path that is taken while a program is being executed. Generally, all the programs have at least one thread,
known as the main thread, that is provided by the JVM or Java Virtual Machine at the starting of the program’s execution. At this point,
when the main thread is provided, the main() method is invoked by the main thread.
• A thread is an execution thread in a program. Multiple threads of execution can be run concurrently by an application running on the Java
Virtual Machine. The priority of each thread varies. Higher priority threads are executed before lower priority threads.
• Thread is critical in the program because it enables multiple operations to take place within a single method. Each thread in the program
often has its own program counter, stack, and local variable.
• Every java application has at least one thread - main thread. Although there are so many other java threads running in background like
memory management, system management, signal processing etc. But from application point of view - main is the first java thread and we
can create multiple threads from it. Multithreading refers to two or more threads executing concurrently in a single program. A computer
single core processor can execute only one thread at a time and time slicing is the OS feature to share processor time between different
processes and threads.
Java Thread Benefits
• Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
• Threads share their parent process data and code
• Context switching between threads is usually less expensive than between processes.
• Thread intercommunication is relatively easy than process communication.
CREATING THREAD package com.journaldev.threads;
Java provides two ways to create a thread public class MyThread extends Thread {
programmatically.
public MyThread(String name) {
1. Extending the java.lang.Thread class . super(name);
2. Implementing the java.lang.Runnable }
interface.
@Override
public void run() {
1. Extending java.lang.Thread class System.out.println("MyThread - START "+Thread.currentThread().getName());
try {
In this case, a thread is created by a new class Thread.sleep(1000);
that extends the Thread class, creating an
instance of that class. The run() method includes //Get database connection, delete unused data from DB
the functionality that is supposed to be doDBProcessing();
implemented by the Thread. We can extend } catch (InterruptedException e) {
java.lang.Thread class to create our own java e.printStackTrace();
thread class and override run() method. Then we
can create it’s object and call start() method to }
execute our custom java thread class run System.out.println("MyThread - END "+Thread.currentThread().getName());
method. Here is a simple java thread example }
showing how to extend Thread class.
}
2. Implementing Runnable interface
}
Lifecycle of a Thread in Java
The Life Cycle of a Thread in Java refers to the state transformations of a thread that begins with its birth and
ends with its death. When a thread instance is generated and executed by calling the start() method of the
Thread class, the thread enters the runnable state. When the sleep() or wait() methods of the Thread class are
called, the thread enters a non-runnable mode.
Thread returns from non-runnable state to runnable state and starts statement execution. The thread dies when it
exits the run() process. In Java, these thread state transformations are referred to as the Thread life cycle.
New State
As we use the Thread class to construct a thread entity, the thread is born and is defined as being in the New state.
That is, when a thread is created, it enters a new state, but the start() method on the instance has not yet been invoked.
Runnable State
A thread in the runnable state is prepared to execute the code. When a new thread's start() function is called, it enters
a runnable state.
In the runnable environment, the thread is ready for execution and is awaiting the processor's availability (CPU time).
That is, the thread has entered the queue (line) of threads waiting for execution.
Running State
Running implies that the processor (CPU) has assigned a time slot to the thread for execution. When a thread from
the runnable state is chosen for execution by the thread scheduler, it joins the running state.
In the running state, the processor allots time to the thread for execution and runs its run procedure. This is the state
in which the thread directly executes its operations. Only from the runnable state will a thread enter the running state.
Blocked State
When the thread is alive, i.e., the thread class object persists, but it cannot be selected for execution by the scheduler.
It is now inactive.
Dead State
When a thread's run() function ends the execution of sentences, it automatically dies or enters the dead state. That is,
when a thread exits the run() process, it is terminated or killed. When the stop() function is invoked, a thread will also
go dead.
Thread Methods
Thread methods in Java are very important while you're start() v/s run() states of thread in Java
working with a multi-threaded application. The thread
class has some important methods which are described
by the thread itself.
• Java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of
thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be
given by the programmer explicitly.
• Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is
represented by numbers ranging from 1 to 10.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
HOW TO GET AND SET PRIORITY OF A THREAD IN JAVA
4. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
5. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1) and maximum(10) limit.
import java.lang.*;
class ThreadDemo extends Thread {
// Method 1 Output
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}
// Main driver method
public static void main(String[] args)
{
// Creating random threads
// with the help of above class
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "+ t1.getPriority());
// Thread 1 Output explanation:
// Display the priority of above thread •Thread with the highest priority will get an execution chance prior to other threads. Suppose
System.out.println("t2 thread priority : "+ t2.getPriority());
// Thread 3 there are 3 threads t1, t2, and t3 with priorities 4, 6, and 1. So, thread t2 will execute first based
System.out.println("t3 thread priority : "+ t3.getPriority()); on maximum priority 6 after that t1 will execute and then t3.
// Setting priorities of above threads by passing integer arguments •The default priority for the main thread is always 5, it can be changed later. The default priority
t1.setPriority(2);
t2.setPriority(5); for all other threads depends on the priority of the parent thread.
t3.setPriority(8);
// t3.setPriority(21); will throw
// IllegalArgumentException 2
System.out.println("t1 thread priority : "+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "+ t2.getPriority());
// 8
System.out.println("t3 thread priority : "+ t3.getPriority());
// Main thread
// Displays the name of currently executing Thread
System.out.println("Currently Executing Thread : "+ Thread.currentThread().getName());
System.out.println( "Main thread priority : "+ Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
}
}
THREAD SYNCHRONIZATION
Thread synchronization in java is a way of programming several threads to carry out
independent tasks easily. It is capable of controlling access to multiple threads to a
particular shared resource. The main reason for using thread synchronization are as
follows:
• To prevent interference between threads.
• To prevent the problem of consistency. Importance of Thread Synchronization in Java
•Thread synchronization in java is used to avoid the error called
Types of Thread Synchronization memory consistency which is caused due to inconsistency view of
In Java, there are two types of thread synchronization: shared memory.
•If a method is declared synchronized then the thread holds that object
1. Process synchronization of the thread until the other thread is done executing.
•It is used for controlling the access of multiple threads and to access
2. Thread synchronization shared resources.
•It avoids the deadlock situations in the thread.
Process synchronization- The process means a program in execution and runs
independently isolated from other processes. CPU time, memory, etc resources are
allocated by the operating system.
Thread synchronization- It refers to the concept where only one thread is executed at
a time while other threads are in the waiting state. This process is called thread
synchronization. It is used because it avoids interference of thread and the problem of
inconsistency. In java, thread synchronization is further divided into two types:
Mutual exclusive- it will keep the threads from interfering with each other while
sharing any resources.
Inter-thread communication- It is a mechanism in java in which a thread running in
the critical section is paused and another thread is allowed to enter or lock the same
critical section that is executed.
Mutual Exclusive
public class Table
It is used for preventing threads from interfering with each other {
void printTable(int n) // non synchronized method
and to keep distance between the threads. Mutual exclusive is {
achieved using the following: for(int i = 1; i <= 5; i++)
{
•Synchronized Method System.out.println(n * i);
•Synchronized Block try
{
•Static Synchronization Thread.sleep(500);
1. Synchronized method It is a method that can be declared }
catch(InterruptedException ie)
synchronized using the keyword “synchronized” before the method {
System.out.println(ie);
name. By writing this, it will make the code in a method thread- }
safe so that no resources are shared when the method is executed. }}
}
Syntax: public class Thread1 extends Thread
synchronized public void methodName() { } {
Table t; // Declaring t as class type table
Method Description
public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of them is chosen to
be awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
1.public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1.public final void notifyAll()
What is Polling, and what are the problems with it?