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

Unit 9 Multithreading

Uploaded by

gaytrip19
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)
11 views

Unit 9 Multithreading

Uploaded by

gaytrip19
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
You are on page 1/ 32

Multi Threading In Java

Subject: Object Oriented Programming Language using JAVA

Faculty Name: Bhushan Shewale.


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.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

Que: What is Thread in java?


Ans: 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.
Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:
New: Whenever a new thread is created, it is always in the new state.
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.
Running: When the thread gets the CPU, it moves from the runnable to the running state.
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.
Terminated: A thread reaches the termination state because of the following reasons:
• When a thread has finished its job, then it exists or terminates normally.
• Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.

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. run(): is used to perform action for a thread.
2. start(): starts the execution of the thread. JVM calls the run() method on the thread.
3. sleep(long milliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. join(): waits for a thread to die.
5. join(long milliseconds): waits for a thread to die for the specified milliseconds.
6. int getPriority(): returns the priority of the thread.
7. int setPriority(int priority): changes the priority of the thread.
8. String getName(): returns the name of the thread.
9. setName(String name): changes the name of the thread.
10. Thread currentThread(): returns the reference of currently executing thread.
11. int getId(): returns the id of the thread.
12. Thread State getState(): returns the state of the thread.
13. boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. suspend(): is used to suspend the thread(deprecated).
16. public void resume(): is used to resume the suspended thread(deprecated).
17. public void stop(): is used to stop the thread(deprecated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread: The start() method of Thread class is used to start a newly created
thread. It performs the following tasks:
• A new thread starts(with new call stack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.
Thread Scheduler in Java
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.
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.
Thread Scheduler Algorithms
On the basis of the above-mentioned factors, the scheduling algorithm is followed by a Java
thread scheduler.
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:

Thread Time of Arrival


t1 0
t2 1
t3 2
t4 3
In the pervious table, we can see that Thread t1 has arrived first, then Thread t2, then t3, and
at last t4, and the order in which the threads will be processed is according to the time of
arrival of threads.

Hence, Thread t1 will be processed first, and Thread t4 will be processed last.
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.
In the above diagram, 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.
Pre-emptive-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.
Working of the Java Thread Scheduler
Let's understand 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. 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:


Following are the syntax of the sleep() method.
1. public static void sleep(long mls) throws InterruptedException
2. public static void sleep(long mls, int n) throws InterruptedException
Que: Can we start a thread twice?
Ans: No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.
Que: What if we call Java run() method directly instead start() method?
Ans: 1. Each thread starts in a separate call stack.
2. Invoking the run() method from the main thread, the run() method goes onto the current
call stack rather than at the beginning of a new call stack.
join() method
The join() method in Java is provided by the java.lang.Thread class that permits one
thread to wait until the other thread to finish its execution. Suppose bh be the object the
class Thread whose thread is doing its execution currently, then the bh.join(); statement
ensures that bh is finished before the program does the execution of the next statement.
When there are more than one thread invoking the join() method, then it leads to
overloading on the join() method that permits the developer or programmer to mention the
waiting period.
Description of The Overloaded join() Method
join(): When the join() method is invoked, the current thread stops its execution and the
thread goes into the wait state. The current thread remains in the wait state until the thread
on which the join() method is invoked has achieved its dead state.
Syntax:
1. public final void join() throws InterruptedException

Naming Thread and Current Thread


A. Naming Thread: The Thread class provides methods to change and get the name of a
thread. By default, each thread has a name, i.e. thread-0, thread-1 and so on. By we can
change the name of the thread by using the setName() method.
The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
B. Current Thread: The currentThread() method returns a reference of the currently
executing thread.
Syntax:
1. public static Thread currentThread();
Priority of a Thread (Thread Priority):
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.
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
and the value of MAX_PRIORITY is 10.

Daemon Thread
Daemon thread 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.
Points to remember for Daemon Thread in Java
• 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.
Java Thread Pool
Java Thread pool represents a group of worker threads that are waiting for the job and
reused many times. A thread pool reuses previously created threads to execute current
tasks
In the case of a thread pool, a group of fixed-size threads is created. A thread from the
thread pool is pulled out and assigned a job by the service provider.
Thread Pool Methods.
1. newFixedThreadPool(int s): The method creates a thread pool of the fixed size s.
2. newCachedThreadPool(): The method creates a new thread pool that creates the new
threads when needed but will still use the previously created thread whenever they are
available to use.
3. newSingleThreadExecutor(): The method creates a new thread.
Advantage of Java Thread Pool
1. Better performance: It saves time because there is no need to create a new thread.
2. Real time usage: It is used in Servlet and JSP where the container creates a thread pool
to process the request.
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such a
way, we can suspend, resume or interrupt a group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class. A ThreadGroup
represents a set of threads. A thread group can also include the other thread group. The
thread group creates a tree in which every thread group except the initial thread group has a
parent. A thread is allowed to access information about its own thread group, but it cannot
access the information about its thread group's parent thread group or any other thread
groups.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.

No. Constructor Description

creates a thread group with


1 ThreadGroup (String name)
given name.

ThreadGroup(ThreadGroup creates a thread group with a


2
parent, String name) given parent group and name.
Java Shutdown Hook
A special construct that facilitates the developers to add some code that has to be run
when the Java Virtual Machine (JVM) is shutting down is known as the Java shutdown
hook. The Java shutdown hook comes in very handy in the cases where one needs to
perform some special cleanup work when the JVM is shutting down.
When does the JVM shut down?
The JVM shuts down when:
• user presses ctrl+c on the command prompt
• System.exit(int) method is invoked
• user logoff
• user shutdown etc.
The addShutdownHook (Thread hook) method
The addShutdownHook () method of the Runtime class is used to register the thread with the
Virtual Machine.
Syntax:
1. public void addShutdownHook(Thread hook){}
Que: How to perform single task by multiple threads in Java?
Ans: If you have to perform a single task by many threads, have only one run() method.
Que: How to perform multiple tasks by multiple threads (multitasking in
multithreading)?
Ans: If you have to perform multiple tasks by multiple threads , have multiple run() methods.
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
How can an object be unreferenced?
There are many ways:
• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.

1) By nulling a reference:
i. Employee e=new Employee();
ii. e=null;

2) By assigning a reference to another:


i. Employee e1=new Employee();
ii. Employee e2=new Employee();
iii. e1=e2; //now the first object referred by e1 is available for garbage collection

3) By anonymous object:
i. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in Object
class as:
1. protected void finalize(){}
gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
1. public static void gc(){}

You might also like