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

Concept of Thread_1

The document provides an overview of threads in Java, defining them as lightweight subprocesses that allow for multithreading, which is the simultaneous execution of multiple threads. It explains the lifecycle of a thread, its states (New, Active, Blocked, Timed Waiting, Terminated), and how to create and manage threads using the Thread class and Runnable interface. Additionally, it discusses thread priorities, the role of the thread scheduler, and various scheduling algorithms used in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Concept of Thread_1

The document provides an overview of threads in Java, defining them as lightweight subprocesses that allow for multithreading, which is the simultaneous execution of multiple threads. It explains the lifecycle of a thread, its states (New, Active, Blocked, Timed Waiting, Terminated), and how to create and manage threads using the Thread class and Runnable interface. Additionally, it discusses thread priorities, the role of the thread scheduler, and various scheduling algorithms used in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 81

Concept of Thread

• Thread:
• we can define threads as a subprocess with lightweight
with the smallest unit of processes and also has
separate paths of execution.
• A Java process is a program in execution.
• A Java thread is a subset of a Java process.

• Multithreading in Java is a process of executing


multiple threads simultaneously.
• Java Multithreading is mostly used in games, animation,
etc.
• All Java programs have at least one thread, known as
the main thread, which is created by the
Java Virtual Machine (JVM) at the program’s start, when
the main() method is invoked.
• In Java, creating a thread is accomplished by
implementing an interface and extending a class.
• Every thread in Java is created and controlled by
the java.lang.Thread class.
• 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.
At a time one thread is executed only.
• Java Thread class
• Java provides Thread class to achieve thread
programming.
• Thread class provides constructors and methods to
create and perform operations on a thread.
• Thread class extends Object class and implements
Runnable interface.
Java Thread Method
Life cycle of a Thread (Thread
States)
• In Java, a thread always exists in any one of the
following states. These states are:
1.New
2.Active
3.Blocked / Waiting
4.Timed Waiting
5.Terminated
• New:
• Whenever a new thread is created, it is always in the
new state.
• For a thread in the new state, the code has not been
run yet and thus has not begun its execution.
• Active:
• When a thread invokes the start() method, it moves
from the new state to the active state.
• The active state contains two states within it: one
is runnable, and the other is running.
• Runnable:
• A thread, that is ready to run is then moved to the
runnable state.
• In the runnable state, the thread may be running or
may be ready to run at any given instant of time.
• It is the duty of the thread scheduler to provide the
thread time to run, i.e., moving the thread the running
state.
• A program implementing multithreading acquires a
fixed slice of time to each individual thread.
• Each and every thread runs for a short span of time and
when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that
the other threads can also run for their slice of time.
• Whenever such a scenario occurs, all those threads that
are willing to run, waiting for their turn to run, lie in the
runnable state. In the runnable state, there is a queue
where the threads lie.
• Running:
• When the thread gets the CPU, it moves from the
runnable to the running state.
• Generally, the most common change in the state of a
thread is from runnable to running and again back to
runnable.
• Blocked or Waiting:
• Whenever a thread is inactive for a span of time (not
permanently) then, either the thread is in the blocked
state or is in the waiting state.
• For example, a thread (let's say its name is A) may want to print
some data from the printer.
• However, at the same time, the other thread (let's say its name is
B) is using the printer to print some data.
• Therefore, thread A has to wait for thread B to use the printer.
Thus, thread A is in the blocked state.
• A thread in the blocked state is unable to perform any execution
and thus never consume any cycle of the Central Processing Unit
(CPU).
• Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked
state.
• Timed Waiting State
• Sometimes the longer duration of waiting for threads
causes starvation, if we take an example like there are
two threads T1, T2 waiting for CPU and T1 is undergoing
Critical Coding operation and if it does not exit CPU until
its operation gets executed then T2 will be exposed to
longer waiting with undetermined certainty, In order to
avoid this starvation situation, we had Timed Waiting for
the state to avoid that kind of scenario as in Timed
Waiting, each thread has a time period for which sleep()
method is invoked and after the time expires the
Threads starts executing its task.
• Terminated State
• A thread will be in Terminated State, due to the below
reasons:
• Termination is achieved by a Thread when it finishes its
task Normally.
• Sometimes Threads may be terminated due to unusual
events like segmentation faults, exceptions…etc. and
such kind of Termination can be called Abnormal
Termination.
• A terminated Thread means it is dead and no longer
available.
Why use threads?

• There are many reasons to use threads in your Java


programs. If you use Swing, servlets, RMI, or Enterprise
JavaBeans (EJB) technology, you may already be using
threads without realizing it.
• Some of the reasons for using threads are that they can
help to:
• Make the UI more responsive
• Take advantage of multiprocessor systems
• Simplify modeling
• Perform asynchronous or background processing
How to create a thread in Java

• There are two ways to create a thread:


1.By extending Thread class
2.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)
Commonly used methods of Thread
class:
1.public void run(): is used to perform action for a
thread.

2.public void start(): starts the execution of the


thread.JVM calls the run() method on the thread.
3.public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
4.public void join(): waits for a thread to die.
1.public void join(long miliseconds): waits for a
thread to die for the specified miliseconds.
2.public int getPriority(): returns the priority of the
thread.
3.public int setPriority(int priority): changes the
priority of the thread.
4.public String getName(): returns the name of the
thread.
5.public void setName(String name): changes the
name of the thread.
1.public Thread currentThread(): returns the
reference of currently executing thread.
2.public int getId(): returns the id of the thread.
3.public Thread.State getState(): returns the state of
the thread.
4.public boolean isAlive(): tests if the thread is alive.
5.public void yield(): causes the currently executing
thread object to temporarily pause and allow other
threads to execute.
1.public void suspend(): is used to suspend the
thread(depricated).
2.public void resume(): is used to resume the
suspended thread(depricated).
3.public void stop(): is used to stop the
thread(depricated).
4.public boolean isDaemon(): tests if the thread is a
daemon thread.
5.public void setDaemon(boolean b): marks the
thread as daemon or user thread.
1.public void interrupt(): interrupts the thread.
2.public boolean is Interrupted(): tests if the thread
has been interrupted.
3.public static boolean interrupted(): tests if the
current thread has been interrupted.
• Runnable interface:
• Any class with instances that are intended to be
executed by a thread should implement the Runnable
interface. The Runnable interface has only one method,
which is called run().
• If you are not extending the Thread class, your class
object would not be treated as a thread object.
• So you need to explicitly create the Thread class object.
We are passing the object of your class that implements
Runnable so that your class run() method may execute.
Using the Thread Class: Thread(Runnable r, String name)
Thread.sleep in Java

• The Java Thread class provides the two variant of the


sleep() method. First one accepts only an arguments,
whereas the other variant accepts two arguments.
• The method sleep() is being used to halt the working of
a thread for a given amount of time.
• The time up to which the thread remains in the sleeping
state is known as the sleeping time of the thread.
• After the sleeping time is over, the thread starts its
execution from where it has left.
• The sleep() Method Syntax:
1.public static void sleep(long mls) throws Interrupte
dException
2.public static void sleep(long mls, int n) throws Inter
ruptedException
• The Thread.sleep() method can be used with any
thread.
• It means any other thread or the main thread can
invoke the sleep() method.
• Parameters:
• The following are the parameters used in the sleep()
method.
• mls: The time in milliseconds is represented by the
parameter mls. The duration for which the thread will
sleep is given by the method sleep().
• n: It shows the additional time in nanoseconds up to
which the programmer or developer wants the thread to
be in the sleeping state. The range of n is from 0 to
999999.
• The method does not return anything.
• Whenever the Thread.sleep() methods execute, it
always halts the execution of the current thread.
• Whenever another thread does interruption while the
current thread is already in the sleep mode, then the
InterruptedException is thrown.
• If the system that is executing the threads is busy, then
the actual sleeping time of the thread is generally more
as compared to the time passed in arguments.
However, if the system executing the sleep() method
has less load, then the actual sleeping time of the
thread is almost equal to the time passed in the
argument.
Example of the sleep() method in Java : on the custom thread
Example of the sleep() Method in Java : on the main thread
sleep() Method in Java: When the sleeping time is -ive
• class SleepExample implements Runnable
{
private String threadName;
public SleepExample(String threadName)
{
this.threadName = threadName;
}
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(threadName + " - Count: " + i);
// Pausing the thread for 1 second and 500,000 nanoseconds (1.5 seconds total)
Thread.sleep(1000, 500000);
}
}
catch (InterruptedException e)
{ System.out.println(threadName + " was interrupted.");
}
}
public static void main(String[] args)
{ Thread thread1 = new Thread(new SleepExample("Thread 1"));
Thread thread2 = new Thread(new SleepExample("Thread 2"));
thread1.start();
thread2.start(); } }
stop() method

• The stop() method of thread class terminates the thread


execution. Once a thread is stopped, it cannot be
restarted by start() method.
Syntax:
public final void stop()
public final void stop(Throwable obj)

This method does not return any value.


Concepts of Daemon Thread

• Daemon thread in Java is a service provider thread


that provides services to the user thread.
• Its life depend on the mercy of user threads i.e. when all
the user threads dies, JVM terminates this thread
automatically.
• There are many java daemon threads running
automatically e.g. gc, finalizer etc.
• It provides services to user threads for background
supporting tasks. It has no role in life than to serve user
threads.
• Its life depends on user threads.
• It is a low priority thread.
• Why JVM terminates the daemon thread if there is no
user thread?
• The sole purpose of the daemon thread is that it
provides services to user thread for background
supporting task. If there is no user thread, why should
JVM keep running this thread. That is why JVM
terminates the daemon thread if there is no user thread.
• Methods for Java Daemon thread by Thread class

1) public void is used to mark the


setDaemon(boolean current thread as daemon
status) thread or user thread.

2) public boolean isDaemon() is used to check that


current is daemon.
Priority of a Thread

• Each thread has a priority.


• Priorities are represented by a number between 1 and
10. In most cases, the thread scheduler schedules the
threads according to their priority (known as preemptive
scheduling).
• But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
• Note that not only JVM a Java programmer can also
assign the priorities of a thread explicitly in a Java
program.
• Setter & Getter Method of Thread Priority
• public final int getPriority(): The
java.lang.Thread.getPriority() method returns the
priority of the given thread.
• public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or assign
the priority of the thread to newPriority. The method
throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1 (minimum)
to 10 (maximum).
• 3 constants defined in Thread class:
1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1.
The value of MAX_PRIORITY is 10.
Example of priority of a Thread:
Thread Scheduler
• A component of Java that decides which thread to run or execute
and which thread to wait is called a thread scheduler in Java.
• In Java, a thread is only chosen by a thread scheduler if it is in
the runnable state.
• However, if there is more than one thread in the runnable state,
it is up to the thread scheduler to pick one of the threads and
ignore the other ones.
• There are some criteria that decide which thread will execute
first.
• There are two factors for scheduling a thread
i.e. Priority and Time of arrival.
• Priority: Priority of each thread lies between 1 to 10.
• If a thread has a higher priority, it means that thread
has got a better chance of getting picked up by the
thread scheduler.
• Time of Arrival: Suppose two threads of the same
priority enter the runnable state, then priority cannot be
the factor to pick a thread from these two threads.
• In such a case, arrival time of thread is considered by
the thread scheduler. A thread that arrived first gets the
preference over the other threads.
Thread Scheduler Algorithms

• First Come First Serve Scheduling:


• In this scheduling algorithm, the scheduler picks the
threads thar arrive first in the runnable queue. Observe
the following table:
• Time-slicing scheduling:
• Usually, the First Come First Serve algorithm is non-
preemptive, which is bad as it may lead to infinite
blocking (also known as starvation).
• To avoid that, some time-slices are provided to the
threads so that after some time, the running thread has
to give up the CPU.
• Thus, the other waiting threads also get time to run
their job.
• Each thread is given a time slice of 2 seconds. Thus,
after 2 seconds, the first thread leaves the CPU, and the
CPU is then captured by Thread2. The same process
repeats for the other threads too.
• Preemptive-Priority Scheduling:
• The name of the scheduling algorithm denotes that the
algorithm is related to the priority of the threads.
• Suppose there are multiple threads available in the
runnable state.
• The thread scheduler picks that thread that has the
highest priority. Since the algorithm is also preemptive,
therefore, time slices are also provided to the threads to
avoid starvation.
• Thus, after some time, even if the highest priority
thread has not completed its job, it has to release the
Working of the Java Thread Scheduler
• Suppose, there are five threads that have different arrival
times and different priorities.
• Now, it is the responsibility of the thread scheduler to decide
which thread will get the CPU first.
• The thread scheduler selects the thread that has the highest
priority, and the thread begins the execution of the job.
• If a thread is already in runnable state and another thread
(that has higher priority) reaches in the runnable state, then
the current thread is pre-empted from the processor, and the
arrived thread with higher priority gets the CPU time.
• When two threads (Thread 2 and Thread 3) having the
same priorities and arrival time, the scheduling will be
decided on the basis of FCFS algorithm. Thus, the
thread that arrives first gets the opportunity to execute
first.
Thread in Synchronous and
asynchronous mode.
• Synchronization is the process of allowing threads to
execute one after another.
• It provides the control to access multiple threads to
shared resources.
• When we want to allow one thread to access the shared
resource, then synchronization is the better option.
• Synchronous or Synchronized means "connected", or
"dependent" in some way. In other words, two
synchronous tasks must be aware of one another, and
one task must execute in some way that is dependent
on the other, such as wait to start until the other task
has completed.
Asynchronous means they are totally independent and
neither one must consider the other in any way, either
in the initiation or in execution.
In synchronous mode, threads access shared resources in a coordinated or
serialized manner.
This is usually achieved by using synchronization constructs like synchronized
blocks or methods, ensuring that only one thread can access the critical section at a
time.
• class SharedResource {
• // Shared resource (in this case, a counter)
• private int counter = 0;
• // Synchronized method to ensure only one thread can increment the counter at a time
• public synchronized void increment(String threadName) {
• counter++;
• System.out.println(threadName + " incremented counter to: " + counter);
• }
• }
• class SynchronousThread implements Runnable {
• private SharedResource resource;
• private String threadName
• public SynchronousThread(SharedResource resource, String threadName) {
• this.resource = resource;
• this.threadName = threadName;
• }
• @Override
• public void run() {
• for (int i = 0; i < 5; i++) {
• resource.increment(threadName);
• try {
• Thread.sleep(500); // Simulate some delay
• } catch (InterruptedException e) {
• e.printStackTrace();
• }
• }
• }

• public static void main(String[] args) {


• SharedResource resource = new SharedResource();

• Thread thread1 = new Thread(new SynchronousThread(resource, "Thread 1"));


• Thread thread2 = new Thread(new SynchronousThread(resource, "Thread 2"));

• thread1.start();
• thread2.start();
• }
• In asynchronous mode, multiple threads can execute independently
without coordination. This may lead to issues like race conditions
when they access shared resources concurrently.
• class SharedResourceAsync {
• // Shared resource (in this case, a counter)
• private int counter = 0;

• // Unsynchronized method to increment the counter


• public void increment(String threadName) {
• counter++;
• System.out.println(threadName + " incremented counter to: " + counter);
• }
• }

• class AsynchronousThread implements Runnable {


• private SharedResourceAsync resource;
• private String threadName;

• public AsynchronousThread(SharedResourceAsync resource, String threadName) {


• this.resource = resource;
• this.threadName = threadName;
• @Override
• public void run() {
• for (int i = 0; i < 5; i++) {
• resource.increment(threadName);
• try {
• Thread.sleep(500); // Simulate some delay
• } catch (InterruptedException e) {
• e.printStackTrace();
• }
• }
• }

• public static void main(String[] args) {


• SharedResourceAsync resource = new SharedResourceAsync();

• Thread thread1 = new Thread(new AsynchronousThread(resource, "Thread 1"));


• Thread thread2 = new Thread(new AsynchronousThread(resource, "Thread 2"));

• thread1.start();
• thread2.start();
• }
• }

You might also like