0% found this document useful (0 votes)
3 views22 pages

Multithreading

The document provides an overview of multithreading in Java, explaining its advantages, thread lifecycle, and methods for creating threads. It discusses thread priority, synchronization, and how to implement synchronized methods and statements to manage shared resources. The content is aimed at understanding the fundamentals of multithreading and its application in Java programming.

Uploaded by

princelenka666
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Multithreading

The document provides an overview of multithreading in Java, explaining its advantages, thread lifecycle, and methods for creating threads. It discusses thread priority, synchronization, and how to implement synchronized methods and statements to manage shared resources. The content is aimed at understanding the fundamentals of multithreading and its application in Java programming.

Uploaded by

princelenka666
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED

PROGRAMMING
Multithreading
Prepared by
Dr. Abinash Tripathy
School of Computer Application
KIIT Deemed to be University, Bhubaneswar
Multithreading in Java
• Multithreading in java is a process of executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.
• Multiprocessing and multithreading, both are used to achieve multitasking.
• However, we use multithreading than multiprocessing because threads use a
shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.
Advantage of Java Multithreading

• It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
• You can perform many operations together, so it saves time.
• Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
Thread in Java
• A thread is a lightweight subprocess, the smallest unit of processing. It is a
separate path of execution.
• Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads. It uses a shared memory area.
• As shown in the figure, a thread is executed inside the process.
• There is context-switching between the threads. There can be multiple processes
inside the OS, and one process can have multiple threads.
Life cycle of Thread
• 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.
Life cycle of Thread
Life cycle of Thread
• 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.
How to create Thread in Java
• There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Thread Class

• Thread class provide constructors and methods to create and perform


operations on a thread.
• Thread class extends Object class and implements Runnable interface.
• Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
Create thread using Thread()
• The default Thread() constructor is used to create a new Thread class.

public class ThreadExample extends Thread


{
public static void main (String args[])
{
Thread t1 = new Thread();
[Link]();
[Link]("Thread has been created with name " +[Link]());
}
}

C:\java\lab>java [Link]
Thread has been created with name Thread-0
Create thread using Thread(String str)
• A thread object is created and a name is provided to the same.

public class ThreadExample1 extends Thread


{
public static void main (String args[])
{
Thread t1 = new Thread("java thread");
[Link]();
[Link]("Thread has been created with name " +[Link]());
}
}

C:\java\lab>java ThreadExample1
Thread has been created with name java thread
Create thread using Thread (Runnable R)
• Runnable reference is passed and a new Thread object is created.
class Testing implements Runnable
{
public void run()
{
[Link]("Do something");
}
} C:\java\lab> java ThreadExample2
class ThreadExample2 extends Thread Do something
{ Thread has been created with name Thread-0
public static void main (String args[])
{
Thread t1 = new Thread (new Testing());
[Link]();
[Link](" Thread has been created with name " + [Link]());
}
}
Create thread using Thread (Runnable r, String r)
• A new Thread object by passing a Runnable reference as the first
parameter and also providing a name for the newly generated thread.
class Book implements Runnable
{
public void run()
{
[Link]("Do A task");
}
} C:\java\lab> java ThreadExample3
public class ThreadExample3 extends Thread Do A task
{ Thread has been created with name Book Thread
public static void main (String args[])
{
Thread t1 = new Thread (new Book(), "Book Thread");
[Link]();
[Link]("Thread has been created with name " +[Link]());
}
}
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.
public class ExampleMT implements Runnable
{
public static void main ( String args[])
{
Thread E = new Thread ("demo1");
Thread E1 = new Thread ("demo2");
[Link]();
[Link]();
[Link]("Thread names are following");
[Link]([Link]());
[Link]([Link]());
}
public void run()
{
}
}
C:\java\lab>java ExampleMT
Thread names are following
demo1
demo2
Thread Priority in java
• The number of services assigned to a given thread is referred to as its priority. Any thread
generated in the JVM is given a priority. The priority scale runs from 1 to 10.
• In most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling).
• 1 is considered as lowest priority
• 5 is considered as standard priority
• 10 is considered as highest level of priority
• The main thread's priority is set to 5 by default, and each child thread will have the same priority
as its parent thread. We have the ability to adjust the priority of any thread, whether it is the main
thread or a user-defined thread.
• It is advised to adjust the priority using the Thread class's constants, which are as follows:
1. Thread.MIN_PRIORITY;
2. Thread.NORM_PRIORITY;
3. Thread.MAX_PRIORITY;
import [Link].*; [Link](2);
class ThreadPriority extends Thread [Link](5);
{ [Link](8);
public void run()
{ [Link] ("t1 thread priority :" +[Link]());
[Link]("Inside run method"); [Link] ("t2 thread priority :" +[Link]());
} [Link] ("t3 thread priority :" +[Link]());
public static void main ( String args[])
{ [Link]("Currently Executing Thread : " + [Link]().getName());
ThreadPriority t1 = new ThreadPriority(); [Link]("Main thread priority : " + [Link]().getPriority());
ThreadPriority t2 = new ThreadPriority(); [Link]().setPriority(10);
ThreadPriority t3 = new ThreadPriority(); [Link]("Main thread priority : " + [Link]().getPriority());
}
[Link] ("t1 thread priority :" +[Link]()); }
[Link] ("t2 thread priority :" +[Link]());
[Link] ("t3 thread priority :" +[Link]());

C:\java\lab>java ThreadPriority
t1 thread priority :5
t2 thread priority :5
t3 thread priority :5
t1 thread priority :2
t2 thread priority :5
t3 thread priority :8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Thread Synchronization
• When more than one thread has to use a shared resource, Java finds a way of ensuring that only
one thread uses the resources at one point of time; this is called Synchronization.
• The key concept of synchronization is the monitor. The monitor holds the exclusive lock that can
be hold by only one object at a time. The monitor allows only one thread to execute a synchronized
method on the object at one time.
• When the execution of the synchronized method is complete, the lock on the object is opened and
monitor allow the highest priority runnable thread attempting to invoke a synchronized method to
proceed.
• A thread executing in a synchronized method may determine that it can not proceed, so, it
voluntarily calls wait().
• The notify() method acts as a signal to the waiting thread that the condition satisfied for the
waiting threads.
• The notifyAll() method acts as a signal to all the waiting threads that condition is satisfied but it
can get the access based on the thread priority.
• The keyword synchronized is used to synchronize the thread and there are two way to do this: by
using synchronized methods and using a synchronized statement
Synchronized methods
• If two or more threads modify an object, that methods that carry the
modifications are declared synchronized.
• Constructors need not be synchronized because a new object is
created in only one thread.
• The general method for declaring a method synchronized is the
following:
Modifier synchronized <return_type> <method_name> (parameters)
class ThreadSM implements Runnable
import [Link].*; {
class ClassA ClassA ob1;
Thread t;
{
ThreadSM(ClassA c) C:\java\lab>javac [Link]
synchronized void printvalue () {
{ this.ob1 = c;
try t = new Thread(this); C:\java\lab>java ThreadSM
{ } 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
for(int i=0;i<=5;i++) public void run()
{ {
[Link](i + " "); [Link]();
}
[Link](1000);
public static void main (String args[])
} {
} ClassA ca = new ClassA();
catch (InterruptedException e) ThreadSM one = new ThreadSM(ca);
{ [Link]();
} ThreadSM two = new ThreadSM(ca);
} [Link]();
} ThreadSM three = new ThreadSM(ca);
[Link]();
}
}
Synchronized statements
• As an alternative to declaring a method synchronized, Java shows flexibility.
• The programmer can declare a part of the code as synchronized using
synchronized statement.
• The general syntax of declaring a set of statements synchronized is as
follows:
synchronized <object> <statement>;
• In the case of synchronized statements, we need to specify an object to act
as a monitor for this object.
• Each java object can act as a monitor and hence java object can be
specified synchronized.
import [Link].*; class ThreadSS implements Runnable
class ClassA {
{ ClassA ob1;
synchronized void printvalue () Thread t;
{ ThreadSS(ClassA c)
try {
{ this.ob1 = c;
for(int i=0;i<=5;i++) t = new Thread(this);
{ }
[Link](i + " "); public void run()
[Link]((int)[Link]()*1000); {
} synchronized(ob1)
} {
catch (InterruptedException e) [Link]();
{ }
} }
} public static void main (String args[])
} {
ClassA ca = new ClassA();
ThreadSS one = new ThreadSS(ca);
[Link]();
ThreadSS two = new ThreadSS(ca);
[Link]();
ThreadSS three = new ThreadSS(ca);
[Link]();
C:\java\lab>javac [Link]
}
}
C:\java\lab>java ThreadSS
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5

You might also like