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

Multi Threading

The document discusses multithreading in Java. It defines a thread as the smallest unit of processing that can be scheduled to run by the operating system. Multithreading allows executing multiple threads simultaneously to perform multiple operations at the same time. The advantages of multithreading include not blocking the user, performing many operations together to save time, and not affecting other threads if an exception occurs in a single thread.

Uploaded by

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

Multi Threading

The document discusses multithreading in Java. It defines a thread as the smallest unit of processing that can be scheduled to run by the operating system. Multithreading allows executing multiple threads simultaneously to perform multiple operations at the same time. The advantages of multithreading include not blocking the user, performing many operations together to save time, and not affecting other threads if an exception occurs in a single thread.

Uploaded by

RITIK MANDAL
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Multithreading

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

Advantages of Java Multithreading

• 1) It doesn't block the user because threads are independent and you can perform multiple

operations at the same time.

• 2) You can perform many operations together, so it saves time.

• 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single


What is 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.
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other words, each process allocates a separate
memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
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.
1) void start() It is used to start the execution
of the thread.
2) void run() It is used to do an action for a
thread.
3) static void sleep() It sleeps a thread for the
specified amount of time.
4) static Thread currentThread() It returns a reference to the
currently executing thread
object.
5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the


thread.
7) void setPriority() It changes the priority of the
thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread
object to pause and allow other threads to
execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and


all of its subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.

18) void setDaemon() It marks the thread as daemon or user


20) boolean isinterrupted() It tests whether the thread has been
interrupted.

21) static boolean interrupted() It tests whether the current thread has
been interrupted.

22) static int activeCount() It returns the number of active threads


in the current thread's thread group.

23) Thread.State getState() It is used to return the state of the


thread.

24) ThreadGroup getThreadGrou It is used to return the thread group to


p which this thread belongs
()
25) String toString() It is used to return a string
representation of this thread, including
the thread's name, priority, and thread
Life cycle of a Thread (Thread States)

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
• A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is
no running state.
• But for better understanding the threads, we are explaining it in the 5 states.
• The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:
1. New
• The thread is in new state if you create an instance of Thread class but before
the invocation of start() method.
2. Runnable
• The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3. Running
• The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked)
• This is the state when the thread is still alive, but is currently not eligible to
run.
5. Terminated
• A thread is in terminated or dead state when its run() method exits.
How to create thread
•There are two ways to create a thread:
1.By extending Thread class

2.By implementing Runnable interface.

•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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
1. public Thread.State getState(): returns the state of the thread.

2. public boolean isAlive(): tests if the thread is alive.

3. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads
to execute.

4. public void suspend(): is used to suspend the thread(depricated).

5. public void resume(): is used to resume the suspended thread(depricated).

6. public void stop(): is used to stop the thread(depricated).

7. public boolean isDaemon(): tests if the thread is a daemon thread.

8. public void setDaemon(boolean b): marks the thread as daemon or user thread.

9. public void interrupt(): interrupts the thread.

10. public boolean isInterrupted(): tests if the thread has been interrupted.

11. 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().
• public void run(): is used to perform action for a thread.
Starting a thread:
•start() method of Thread class is used to start a newly created thread. It performs
following tasks:A new thread starts(with new callstack).
•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

•Thread scheduler in java is the part of the JVM that decides which thread should run.

•There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

•Only one thread at a time can run in a single process.

•The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

Difference between preemptive scheduling and time slicing


•Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states
or a higher priority task comes into existence.
• Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready
tasks.
• The scheduler then determines which task should execute next, based on priority and other factors.
Can we start a thread twice?

• No. After starting a thread, it can never be started again. If you does so,
an eIllegalThreadStateException is thrown. In such case, thread will run once but
for second time, it will throw exception.

can we call run() method directly instead start() method?


• Each thread starts in a separate call stack.

• Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
• The join() method
• The join() method waits for a thread to die. In other words, it causes the currently

running threads to stop executing until the thread it joins with completes its task.
• 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 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.


Priority of a Thread (Thread Priority):

• Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular 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.

• 3 constants defined in Thread class:


• Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
• Daemon Thread in Java
• 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.

• You can see all the detail by typing the jconsole in the command prompt. The jconsole tool

provides information about the loaded classes, memory usage, running threads 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.

• Methods:
No. Method Description

1) public void setDaemon(boolean status) is used to mark the current thread as daemon
thread or user thread.

2) public boolean isDaemon() is used to check that current is daemon.


Java Thread Pool
• Java Thread pool represents a group of worker threads that are waiting for the job and
reuse many times.

• In case of thread pool, a group of fixed size threads are created. A thread from the thread
pool is pulled out and assigned a job by the service provider. After completion of the job,

thread is contained in the thread pool again.


Advantage of Java Thread Pool
• Better performance It saves time because there is no need to create new thread.

Real time usage


• It is used in Servlet and JSP where container creates a thread pool to process the request.
Synchronization in Java
• Synchronization in java is the capability to control the access of multiple threads to any shared
resource.

• Java Synchronization is better option where we want to allow only one thread to access the shared
resource
Why use Synchronization?
• The synchronization is mainly used to

1.To prevent thread interference.

2.To prevent consistency problem


Types of Synchronization
• There are two types of synchronization

1.Process Synchronization

2.Thread Synchronization

• Here, we will discuss only thread synchronization.


Thread Synchronization
• There are two types of thread synchronization mutual exclusive and inter-
thread communication.

1.Mutual Exclusive
1. Synchronized method.

2. Synchronized block.

3. static synchronization.

2.Cooperation (Inter-thread communication in java)


Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:

1.by synchronized method

2.by synchronized block

3.by static synchronization


Concept of Lock in Java
• Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock before accessing them, and then
release the lock when it's done with them.

• From Java 5 the package java.util.concurrent.locks contains several lock implementations.


Java synchronized method
• If you declare any method as synchronized, it is known as synchronized method.

• Synchronized method is used to lock an object for any shared resource.

• When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the
method.

• Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.

• If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block

• Synchronized block is used to lock an object for any shared resource.

• Scope of synchronized block is smaller than the method.


Static Synchronization
• If you make any static method as synchronized, the lock will be on the
class not on object
Problem without static synchronization
• Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2.

• In case of synchronized method and synchronized block there cannot be


interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.

• But there can be interference between t1 and t3 or t2 and t4 because t1 acquires


another lock and t3 acquires another lock. We want no interference between t1
and t3 or t2 and t4.Static synchronization solves this problem.
• Deadlock in java
• Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
thread is waiting for an object lock, that is acquired by another thread and second thread
is waiting for an object lock that is acquired by first thread.

• Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.
Inter-thread communication in Java
• Inter-thread communication or Co-operation is all about 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()
• 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 waits until object is notified.
InterruptedException

public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException
• 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:
• public final void notify()
• notifyAll() method
• Wakes up all threads that are waiting on this object's monitor.
Syntax:
• public final void 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.
• Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
• It is because they are related to lock and object has a lock.

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is completed.
methods
• Interrupting a Thread

• If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException.

• If the thread is not in the sleeping or waiting state, calling the interrupt() method performs
normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true.

• Let's first see the methods provided by the Thread class for thread interruption.
The 3 methods provided by the Thread class for interrupting a thread

•public void interrupt()


•public static boolean interrupted()
•public boolean isInterrupted()
The isInterrupted() method returns the interrupted flag either true or false. The static interrupted()
method returns the interrupted flag afterthat it sets the flag to false if it is true

You might also like