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

Thread

The document provides an overview of threads in Java, describing them as lightweight subprocesses that share memory and can operate independently. It explains multitasking through process-based and thread-based approaches, outlines the life cycle of a thread, and details methods for creating and managing threads. Additionally, it covers thread synchronization, deadlock, inter-thread communication, and the importance of thread pools in optimizing performance.

Uploaded by

tikubadmash6969
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 views20 pages

Thread

The document provides an overview of threads in Java, describing them as lightweight subprocesses that share memory and can operate independently. It explains multitasking through process-based and thread-based approaches, outlines the life cycle of a thread, and details methods for creating and managing threads. Additionally, it covers thread synchronization, deadlock, inter-thread communication, and the importance of thread pools in optimizing performance.

Uploaded by

tikubadmash6969
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

Thread

Moyn
What is Thread in java?
A thread is a lightweight sub process, a 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 shares a common memory area.

As shown in the above figure, 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.
Note: At a time one thread is executed only.
Moyn
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved by two ways:

1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
➢ The Each process have its own address in memory i.e. each process allocates separate memory area.
➢ Process is heavyweight.
➢ Cost of communication between the process is high.
➢ Switching from one process to another require some time for saving and loading registers, memory
maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
Multithreading in java is a process of executing multiple threads simultaneously.
➢ Threads share the same address space.
➢ Thread is lightweight.
➢ Cost of communication between the thread is low.
➢ We can achieve parallel execution
➢ We can have efficient usage of processor time

Note: At least one process is required for each thread. Moyn


Life cycle of a Thread (Thread States)
A thread can be in one of the five states. The life cycle of the thread in java is
controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
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. Moyn
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.

Moyn
How to create thread
There are two ways to create a thread:
1. By implementing Runnable interface.
2. By extending Thread class
1) 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.

Note: If you are not extending the Thread class,your class object would not be treated as a thread
[Link] you need to explicitely create Thread class [Link] are passing the object of your class that
implements Runnable so that your class run() method may execute.

2) Thread class:
➢ Thread class provide constructors and methods to create and perform operations on a [Link]
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) Cont…… Moyn
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 [Link] 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 int getPriority(): returns the priority of the thread.
5) public int setPriority(int priority): changes the priority of the thread.
6) public String getName(): returns the name of the thread.
7) public void setName(String name): changes the name of the thread.
8) public Thread currentThread(): returns the reference of currently executing thread.
9) public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to
execute.

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.

Can we start a thread twice?


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.
Moyn
Sleep() method of Thread class

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java


The Thread class provides methods for sleeping a thread:

public static void sleep(long miliseconds)throws InterruptedException

Note: . As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.

Moyn
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
➢ A public String getName(): is used to return the name of a thread.
➢ public void setName(String name): is used to change the name of a thread.

The currentThread() method:


The currentThread() method returns a reference to the currently executing thread object.

Syntax of currentThread() method:


public static Thread currentThread(): returns the reference of currently running thread.

Moyn
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 defiend 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.

Moyn
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.
Points to remember for Daemon Thread in Java
1) It provides services to user threads for background supporting tasks. It has no role in life than to serve user
threads.
2) Its life depends on user threads.
3) 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
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.

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw
IllegalThreadStateException. Moyn
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.

Moyn
Synchronization
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.

Thread Synchronization
1. Synchronized method.
2. Synchronized block.

Moyn
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.
➢ Scope of synchronized block is smaller than the method.

Moyn
Deadlock
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.

Moyn
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized threads
to communicate with each [Link] implemented by following methods of Object class:
wait()
notify()
notifyAll()
1) 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.

Method Description
public final void wait()throws waits until object is notified.
InterruptedException
public final void wait(long waits for the specified amount of
timeout)throws time.
InterruptedException

Moyn
2) 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()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

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

Difference between wait and sleep?


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
should be notified by notify() or after the specified amount of time,
notifyAll() methods sleep is completed.

Moyn
THANK YOU

You might also like