Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views16 pages

Notes On Thread

Multithreading in Java allows multiple threads to execute concurrently, improving CPU utilization and application performance. It involves dividing a program into subprograms (threads) that can run simultaneously, with advantages such as reduced computation time and independent thread execution. However, it also introduces complexities like synchronization issues and debugging challenges.

Uploaded by

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

Notes On Thread

Multithreading in Java allows multiple threads to execute concurrently, improving CPU utilization and application performance. It involves dividing a program into subprograms (threads) that can run simultaneously, with advantages such as reduced computation time and independent thread execution. However, it also introduces complexities like synchronization issues and debugging challenges.

Uploaded by

sucharita.sit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

https://www.youtube.com/watch?

v=TCd8QIS-2KI

Multithreading
Multithreading means multiple threads of execution concurrently. The process of executing
multiple threads simultaneously (concurrently) is called multithreading in Java.

In other words, multithreading is a technique or programming concept in which a program


(process) is divided into two or more subprograms (subprocesses), each of which can perform
different tasks simultaneously (at the same time and in parallel manner). Each subprogram of a
program is called thread in Java.

Look at the below figure where a Java program has three threads, one main and two others. The
other two threads, ThreadA and ThreadB are created and started from the main thread.

When a program contains multiple flows of control, it is called multithreaded program.

Once initiated by the main thread, thread ThreadA and ThreadB run simultaneously and share
the resources together. It is the same as people living in a joint family and sharing certain
resources among all of them.

When a program contains more than one thread, the CPU can switch between two threads to execute
them at the same time. The switching between two threads is known as context switch.
The switching from one thread to another thread occurs so fast that it appears to the users that all
threads are being executed at the same time. But in reality, only one thread is executed at a time.

This technique is useful for those applications which need multiple tasks to be done
simultaneously. In a single processor system, multiple threads share CPU time that is known as
time-sharing.

The operating system is responsible for allocating and scheduling resources to them. Thus,
multithreading improves the performance of CPU by maximum utilization and keeping the idle
time of CPU to minimum.

In a multithreaded program, each thread is assigned a single task to perform and executes
independently. If an exception occurs in one thread, it does not affect other threads during the
execution.

For example, one thread read data, another thread process it, and third thread write it, thus
improves the overall performance of an application.

We can write a multithreaded program to display animations, to play music, and download a file
from the network at the same time.

Advantage of Multithreading in Java

The advantages of using multithreading programming concept are as follows:

1. In a multithreaded application program, different parts of the application are executed by


different threads. The entire application does not stop even if an exception occurs in any of the
threads. It does not affect other threads during the execution of the application.

2. Different threads are allotted to different processors and each thread is executed in different
processors in parallel.

3. Multithreading helps to reduce computation time.

4. Multithreading technique improves the performance of the application.

5. Threads share the same memory address space. Hence, it saves memory.

6. Multithreaded program makes maximum utilization of CPU and keeping the idle time of CPU
to minimum.
7. Context switching from one thread to another thread is less expensive than between processes.

Drawbacks of Multithreading in Java

The drawbacks of multithreading are as follows:

1. Increased complexity.
2. Synchronization of shared resources.
3. In the multithreading programming concept, debugging is difficult. At times, result is
unpredictable.
4. Potential deadlocks.
5. Programming complications may occur.

Multitasking in Java

The process of executing one or more tasks concurrently or at the same time is called
multitasking. It is the ability of an operating system to execute multiple tasks at once. The main
purpose of multitasking is to use the idle time of CPU.

Multitasking can be implemented in two ways:

1. Process-based multitasking (Multiprocessing)


2. Thread-based multitasking (Multithreading)

Process-based Multitasking (Multiprocessing)

The process of executing multiple programs or processes at the same time (concurrently) is
called process-based multitasking or program-based multitasking. In process-based multitasking,
several programs are executed at the same time by the microprocessor.

Therefore, it is also called multiprocessing in Java. It is a heavyweight. A process-based


multitasking feature allows to execute two or more programs concurrently on the computer.

A good example is, running spreadsheet program while also working with word-processor.

Each program (process) has its own address space in the memory. In other words, each program
is allocated in a separate memory area.

The operating system requires some CPU time to switch from one program to another program.
The switching of CPU among programs is called context switching.
The switching from one program to another program is so fast that it appears to the user that
multiple tasks are being done at the same time.

Thread-based Multitasking (Multithreading)

A thread is a separate path of execution of code for each task within a program. In thread-based
multitasking, a program uses multiple threads to perform one or more tasks at the same time by a
processor.

That is, thread-based multitasking feature allows you to execute several parts of the same
program at once. Each thread has a different path of execution.

Realtime Example of Multithreading in Java

Let’s take different examples of thread-based multithreading in Java.

1. A very good example of thread-based multithreading is a word processing program that


checks the spelling of words in a document while writing the document. This is possible only if
each action is performed by a separate thread.

2. Another familiar example is a browser that starts rendering a web page while it is still
downloading the rest of page.

Consider a program as shown in the below figure. The program is divided into two parts. These
parts may represent two separate blocks of code or two separate methods that can perform two
different tasks of the same program.

Hence, a processor will create two separate threads to execute these two parts simultaneously.
Each thread acts as an individual process that will execute a separate block of code.

Thus, a processor has two threads that will perform two different tasks at a time. This
multitasking is called thread-based multiple tasking.

Advantage of Thread-based Multitasking over Process-


Thread Multitasking

The main advantages of thread-based multitasking as compared to process-based tasking are

1. Threads share the same memory address space.

2. Context switching from one thread to another thread is less expensive than between processes.

3. The cost of communication between threads is relatively low.

4. Threads are lightweight as compared to processes (heavyweight). They utilize the minimum
resources of the system. They take less memory and less processor time.
Java supports thread-based multitasking and provides a high quality of facilities for
multithreading programming.

A great way to remember the difference between process-based multitasking and thread-based
multitasking is process-based multitasking works with multiple programs or processes whereas
thread-based multitasking works with parts of one program.

In process-based multitasking, a program is the smallest unit of executable code whereas, in


thread-based multitasking, thread is the smallest unit of executable code.

Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantage of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at 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 exception occur in a single
thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved by two ways:
 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)

 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)

 Threads share the same address space.


 Thread is lightweight.
 Cost of communication between the thread is low.

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.
Life Cycle of Thread in Java | Thread State
Life Cycle of Thread in Java is basically state transitions of a thread that starts from its birth
and ends on its death.

When an instance of a thread is created and is executed by calling start() method of Thread class,
the thread goes into runnable state.

When sleep() or wait() method is called by Thread class, the thread enters into non-runnable
state.

From non-runnable state, thread comes back to runnable state and continues execution of
statements.

When the thread comes out of run() method, it dies. These state transitions of a thread are called
Thread life cycle in Java.

To work with threads in a program, it is important to identify thread state. So. let’s understand
how to identify thread states in Java thread life cycle.

Thread States in Java

A thread is a path of execution in a program that enters any one of the following five states
during its life cycle. The five states are as follows:

1. New

2. Runnable

3. Running

4. Blocked (Non-runnable state)

5. Dead
1.New (Newborn State): When we create a thread object using Thread class, thread is born and
is known to be in Newborn state. That is, when a thread is born, it enters into new state but the
start() method has not been called yet on the instance.

In other words, Thread object exists but it cannot execute any statement because it is not an
execution of thread. Only start() method can be called on a new thread; otherwise, an
IllegalThreadStateException will be thrown.
2.Runnable state: Runnable state means a thread is ready for execution. When the start()
method is called on a new thread, thread enters into a runnable state.

In runnable state, thread is ready for execution and is waiting for availability of the processor
(CPU time). That is, thread has joined queue (line) of threads that are waiting for execution.

If all threads have equal priority, CPU allocates time slots for thread execution on the basis of
first-come, first-serve manner. The process of allocating time to threads is known as time
slicing. A thread can come into runnable state from running, waiting, or new states.

3.Running state: Running means Processor (CPU) has allocated time slot to thread for its
execution. When thread scheduler selects a thread from the runnable state for execution, it goes
into running state. Look at the above figure.

In running state, processor gives its time to the thread for execution and executes its run method.
This is the state where thread performs its actual functions. A thread can come into running state
only from runnable state.

A running thread may give up its control in any one of the following situations and can enter into
the blocked state.
a) When sleep() method is invoked on a thread to sleep for specified time period, the thread is
out of queue during this time period. The thread again reenters into the runnable state as soon as
this time period is elapsed.

b) When a thread is suspended using suspend() method for some time in order to satisfy some
conditions. A suspended thread can be revived by using resume() method.

c) When wait() method is called on a thread to wait for some time. The thread in wait state can
be run again using notify() or notifyAll() method.

4.Blocked state: A thread is considered to be in the blocked state when it is suspended, sleeping,
or waiting for some time in order to satisfy some condition.

5.Dead state: A thread dies or moves into dead state automatically when its run() method
completes the execution of statements. That is, a thread is terminated or dead when a thread
comes out of run() method. A thread can also be dead when the stop() method is called.

During the life cycle of thread in Java, a thread moves from one state to another state in a variety
of ways. This is because in multithreading environment, when multiple threads are executing,
only one thread can use CPU at a time.
All other threads live in some other states, either waiting for their turn on CPU or waiting for
satisfying some conditions. Therefore, a thread is always in any of the five states.

Thread Class in Java | Thread Methods in


Java
In Java, Thread class contains several constructors for creating threads for tasks and methods for
controlling threads. It is a predefined class declared in java.lang default package.

Each thread in Java is created and controlled by a unique object of the Thread class. An object of
thread controls a thread running under JVM.

Thread class contains various methods that can be used to start, control, interrupt the execution
of a thread, and for many other thread related activities in a program.

Thread class extends Object class and it implements Runnable interface. The declaration of
thread class is as follows:

public class Thread


extends Object
implements Runnable
Look at the below figure that shows class diagram of Java Thread class.

Thread Class Constructor

The various constructors of thread class are defined in java.lang package that can be used to
create an object of thread are as follows:

1. Thread(): This is a basic and default constructor without parameters. It simply creates an
object of Thread class.

2. Thread(String name): It creates a new thread object with specified name to a thread.

3. Thread(Runnable r): It creates a thread object by passing a parameter r as a reference to an


object of the class that implements Runnable interface.

4. Thread(Runnable r, String name): This constructor creates a thread object by passing two arguments
r and name. Here, variable r is a reference of an object of class that implements Runnable interface.

Methods of Thread Class in Java


Thread class provides various static methods that are as follows:

1. currentThread(): The currentThread() returns the reference of currently executing thread.


Since this is a static method, so we can call it directly using the class name. The general syntax
for currentThread() is as follows:

Syntax:

public static Thread currentThread()

2. sleep(): The sleep() method puts currently executing thread to sleep for specified number of
milliseconds. This method is used to pause the current thread for specified amount of time in
milliseconds.

Since this method is static, so we can access it through Thread class name. The general syntax of
this method is as follows:

Syntax:

public static void sleep(long milliseconds) throws InterruptedException

The general syntax for overloaded version of sleep method is as follows:

Syntax:

public static void sleep(long milliseconds, int nanoseconds ) throw


InterruptedException

The overloaded version of sleep() method is used to pause specified period of time in
milliseconds and nanoseconds. Both methods throw InterruptedException and must be used
within Java try-catch block.

3. yield(): The yield() method pauses the execution of current thread and allows another thread of equal
or higher priority that are waiting to execute. Currently executing thread give up the control of the CPU.
The general form of yield() method is as follows:

Syntax:

public static void yield()

4. activeCount(): This method returns the number of active threads.

Syntax:
public static intactiveCount()

Since this method is static, so it can be accessed through Thread class name. It does not accept
anything.

The instance methods of Thread class are as follows:

1. start(): The start() method is used to start the execution of a thread by calling its run() method.
JVM calls the run() method on the thread. The general syntax for start() method is as follows:

Syntax:

public void start()

2. run(): The run() method moves the thread into running state. It is executed only after the
start() method has been executed. The general syntax is as follows:

Syntax:

public void run()

3. getName(): This method returns the name of the thread. The return type of this method is
String. The general form of this method is:

Syntax:

public final String getName()

4. setName(): This method is used to set the name of a thread. It takes an argument of type
String. It returns nothing.

Syntax:

public final void setName(String name)

5. getPriority(): This method returns the priority of a thread. It returns priority in the form of an
integer value ranging from 1 to 10. The maximum priority is 10, the minimum priority is 1, and
normal priority is 5.

Syntax:

public final intgetPriority() // Return type is an integer.

6. setPriority(): This method is used to set the priority of a thread. It accepts an integer value as
an argument. The general syntax is given below:

Syntax:
public final void setPriority(intnewPriority)

7. isAlive(): This method is used to check the thread is alive or not. It returns a boolean value
(true or false) that indicates thread is running or not. The isAlive() method is final and native.
The general syntax for isAlive() method is as follows:

Syntax:

public final native booleanisAlive()

8. join(): The join() method is used to make a thread wait for another thread to terminate its
process. The general syntax is

Syntax:

public final void join() throw InterruptedException

This method throws InterruptedException and must be used within a try-catch block.

9. stop(): This method is used to stop the thread. The general form for this method is as follows:

Syntax:

public final void stop()

This method neither accepts anything nor returns anything.

10. suspend(): The suspend() method is used to suspend or pause a thread.

Syntax:

public final void suspend()

11. resume(): This method is used to resume the suspended thread. It neither accepts anything
nor returns anything.

Syntax:

public final void resume()

12. isDaemon(): This method is used to check the thread is daemon thread or not.

Syntax:

public final booleanisDaemon()

You might also like