0% found this document useful (0 votes)
2 views

Unit1_Multithreading

Uploaded by

Swastik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit1_Multithreading

Uploaded by

Swastik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

THREADS

• 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.

private void doDBProcessing() throws InterruptedException {


Thread.sleep(5000);
}

}
2. Implementing Runnable interface

To make a class runnable, we can package com.journaldev.threads;


implement java.lang.Runnable interface
and provide implementation in public void public class HeavyWorkRunnable implements Runnable {
run() method. To use this class as Thread,
we need to create a Thread object by
passing object of this runnable class and @Override
then call start() method to execute the run() public void run() {
method in a separate thread. Here is a java System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
thread example by implementing Runnable try {
interface. Thread.sleep(1000);
//Get database connection, delete unused data from DB
doDBProcessing();
The start() method is used to call the void run()
} catch (InterruptedException e) {
method. When start() is called, a new stack is
e.printStackTrace();
given to the thread, and run() is invoked to
}
introduce a new thread in the program.
System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
}

private void doDBProcessing() throws InterruptedException {


Thread.sleep(5000);
}

}
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.

public void start(): This method to start the thread in a


separate path of execution. Then it invokes the run()
method on the thread object.
public void run(): this method is the starting point of the
thread. The execution of the thread begins from this
process.
public final void setName(): this method changes the
name of the thread object. There is also a getName()
method for retrieving the name of the current context.
public final void setPriority(): you use this method to set Runnable v/s Running States of Thread in Java
the values of the thread object.
public void sleep(): you use this method to suspend the The runnable state of a thread is a state in which the thread is ready to run is said
thread for a particular amount of time. to be in a Runnable state or in other words waiting for other threads (currently
executing) to complete its execution and execute itself. Running State of a thread
public void interrupt(): you use this method to interrupt
where the currently executing in the processor is said to in a Running state. It is
a particular thread. It also causes it to continue execution the responsibility of the thread scheduler to give the thread, time to run.
if it was blocked for any reason.
public final boolean isAlive(): this method returns true if
the thread is alive.
MULTITHREADING IN JAVA
• In Java, multithreading is the method of running two or more threads at the
same time to maximize CPU utilization. As a result, it is often referred to
as Concurrency in Java. Each thread runs in parallel with the others. Since
several threads do not assign different memory areas, they conserve
memory. Furthermore, switching between threads takes less time.
• In Java, multithreading enhances program structure by making it simpler
and easier to navigate. These generalized threads can be used in high-server
media applications to easily change or enhance the configuration of these
complex structures.
How to Handle Thread Deadlock

• A deadlock is a situation in which two or more


threads are stuck waiting for each other
indefinitely. When several threads need the same
locks but receive them in separate orders, a
deadlock occurs. In a Java multithreaded program,
a deadlock condition may occur because the
synchronized keyword causes the executing thread
to block while waiting for the lock, associated with
the specified object.
• To prevent deadlock, make sure that when you
obtain several locks, you always acquire them in
the same order across all threads. Here is an
example of code which may result in a deadlock.
THREAD PRIORITY IN JAVA

• 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

// Declaring parameterized constructor and passing variable t as a parameter to the thread.


Thread1(Table t)
{
this.t = t;
}
public void run()
{
t.printTable(2);
}
}
public class Thread2 extends Thread
{
Table t; // Declaring t as class type table
Thread2(Table t)
{
this.t = t;
} Explanation
public void run()
{ In this example, class thread1 extends the class thread and has a method run that is void. The
t.printTable(10); class thread2 extends the thread and has a method run that is void. Both are printing tables of
}
}
different numbers. In the main class, the object of threads 1 and 2 are created and the method
public class UnsynchronizedMethod
{ .
start is invoked
public static void main(String[] args)
{
// Creating an object of Table class.
Table obj = new Table();
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
t1.start();
t2.start();
}
}
2.Synchronized Block
If a block is declared as synchronized then the code which class Table
is written inside a method is only executed instead of the {
void printTable(int n){
whole code. It is used when sequential access to code is synchronized(this){ //This is a synchronized block
required. for(int i=1;i<=5;i++){
Syntax: System.out.println(n*i);
try{
Thread.sleep(400);
synchronized (object reference)
}catch(Exception e){System.out.println(e);}
{ }
// Insert code here }
} }//end of the synchronized block
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
In this example, class thread1 extends the class thread and has a method run that is
} void. The class thread2 extends the thread and has a method run that is void. Both are
class MyThread2 extends Thread{ printing tables of different numbers. In the main class, the object of threads 1 and 2
Table t;
are created and the method start is invoked. The difference between both examples is
MyThread2(Table t){
this.t=t;
that this is the synchronized thread.
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronizedBlock1{


public static void main(String args[]){
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
3.Static Synchronization // Java program of multithreading with static synchronized
The method is declared static in this case. It means that
lock is applied to the class instead of an object and only class Display
one thread will access that class at a time. {
public static synchronized void wish(String name)
{
Syntax: for(int i=0;i<3;i++)
synchronized static return type class name{}` {
System.out.print("Good Morning: ");
System.out.println(name);
try{ Explanation
Thread.sleep(2000);
} In this example, the class MyThread extends the class thread and
catch(InterruptedException e)
{ has a method run that is void. The same method is printing
} different strings. In the main class, the object of the thread is
} created and the method start is invoked. The difference between
}
} both examples is that this is the static synchronized thread.
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d,String name)
{
this.d=d;
this.name=name;
}
public void run() What is the Difference Between Thread Joining and Thread
{ Synchronization?
d.wish(name); Thread joining in java waits for the thread to be finished completely
}
whereas thread synchronization is used for preventing two threads to be
}
class MainClass executed at the same time in the same piece of code.
{
public static void main(String arg[])
{
Display d1=new Display();
Display d2=new Display();
MyThread t1=new MyThread(d1,"Hello");
MyThread t2=new MyThread(d2,"World");
t1.start();
t2.start();
}
}
THREAD COMMUNICATION

Inter-thread communication or Co-operation is all about Process Of Inter-thread Communication


allowing synchronized threads to communicate with each
other.
Cooperation (Inter-thread communication) is a mechanism in
which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following
methods of Object class:
• wait()
• notify()
• notifyAll()

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor
state of the object.
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it
will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

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?

• The process of testing a condition repeatedly till it becomes


true is known as polling. Polling is usually implemented with
the help of loops to check whether a particular condition is
true or not. If it is true, a certain action is taken. This wastes
many CPU cycles and makes the implementation inefficient. wait() sleep()
• For example, in a classic queuing problem where one thread is
producing data, and the other is consuming it.
The wait() method The sleep() method
How Java multi-threading tackles this problem?
releases the lock. doesn't release the
lock.
To avoid polling, Java uses three methods, namely, wait(),
notify(), and notifyAll(). All these methods belong to object class
as final so that all classes have them. They must be used within a It is a method of Object It is a method of Thread
synchronized block only. class class
• wait(): It tells the calling thread to give up the lock and go to
sleep until some other thread enters the same monitor and calls It is the non-static It is the static method
notify(). method
• notify(): It wakes up one single thread called wait() on the
same object. It should be noted that calling notify() does not It should be notified by After the specified
give up a lock on a resource.
notify() or notifyAll() amount of time, sleep
• notifyAll(): It wakes up all the threads called wait() on the
same object.
methods is completed.

You might also like