0% found this document useful (0 votes)
2 views9 pages

Multithreading in Java Class Notes

Multi threading

Uploaded by

primenogame006
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)
2 views9 pages

Multithreading in Java Class Notes

Multi threading

Uploaded by

primenogame006
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

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.

However, we use multithreading rather than multiprocessing because threads use a


shared memory area. It does not allocate separate memory areas, so it saves memory, and
context-switching between the threads takes less time than a process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1. It does not 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 thread.
4. Multithreading can significantly enhance the performance of applications by making
better use of multiple CPU cores. Each thread can run on a separate core, allowing for
parallel processing and faster execution of tasks.
5. In applications with a graphical user interface (GUI), multithreading can help keep the
interface responsive. Long-running tasks can be handled in the background by separate
threads, preventing the main thread from freezing and improving user experience.
6. Threads within the same process share the same memory and resources, which makes
it easier to share data between them without the need for complex inter-process
communication mechanisms.
7. Using multiple threads can simplify the design of complex applications, allowing for
more modular and manageable code. For example, separate threads can be dedicated to
different tasks, such as network communication, file I/O, and computation.
8. Multithreading allows an application to continue processing while waiting for I/O
operations to complete. It leads to better utilization of CPU resources as threads can
perform useful work during I/O waits.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

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.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

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

What is a 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 an exception occurs in one thread, it does not affect other
threads. It uses a shared memory area.
As shown in the above figure, a 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.

Java Thread Class


Java provides a Thread class to achieve thread programming. The Thread class
provides constructors and methods to create and perform operations on a thread. Thread
class extends the Object class and implements the Runnable interface.

Thread States
New: A thread that has been created but not yet started.

Runnable or Running: A thread that is ready to run and waiting for CPU time.

Waiting: A thread that is waiting indefinitely for another thread to perform a particular
action.

Terminated: A thread that has completed its task.

Java Thread Class Methods


Modifier and Method Description
Type

void start() It is used to start the execution of the thread.

void run() It is used to do an action for a thread.

static void sleep() It sleeps a thread for the specified amount of time.

static Thread currentThread() It returns a reference to the currently executing thread object.

void join() It waits for a thread to die.

int getPriority() It returns the priority of the thread.

void setPriority() It changes the priority of the thread.


String getName() It returns the name of the thread.

void setName() It changes the name of the thread.

long getId() It returns the ID of the thread.

boolean isAlive() It tests if the thread is alive.

static void yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.

void suspend() It is used to suspend the thread.

void resume() It is used to resume the suspended thread.

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

void destroy() It is used to destroy the thread group and all of its subgroups.

boolean isDaemon() It tests if the thread is a daemon thread.

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

void interrupt() It interrupts the thread.

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

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

static int activeCount() It returns the number of active threads in the current thread's
thread group.

void checkAccess() It determines if the currently running thread has permission to


modify the thread.

static boolean holdLock() It returns true if and only if the current thread holds the monitor
lock on the specified object.

static void dumpStack() It is used to print a stack trace of the current thread to the
standard error stream.
StackTraceEle getStackTrace() It returns an array of stack trace elements representing the stack
ment[] dump of the thread.

static int enumerate() It is used to copy every active thread's thread group and its
subgroup into the specified array.

[Link] getState() It is used to return the state of the thread.

ThreadGroup getThreadGrou It is used to return the thread group to which this thread belongs
p()

String toString() It is used to return a string representation of this thread, including


the thread's name, priority, and thread group.

void notify() It is used to give a notification for only one thread that is waiting
for a particular object.

void notifyAll() It is used to give a notification to all waiting threads of a particular


object.

void setContextClass It sets the context ClassLoader for the Thread.


Loader()

ClassLoader getContextClass It returns the context ClassLoader for the thread.


Loader()

Static getDefaultUnca It returns the default handler invoked when a thread abruptly
[Link] ughtExceptionH terminates due to an uncaught exception.
ghtException andler()
Handler

static void setDefaultUnca It sets the default handler invoked when a thread abruptly
ughtExceptionH terminates due to an uncaught exception.
andler()

Thread Life Cycle in Java


In Java, threads go through several distinct states during their lifetime, as defined
in [Link] class. All thread states are Enum constants. A thread can be in
only one state at a given point in time.

These states are virtual machine states which do not reflect any operating system thread
states. A thread can be in one of the following states:

Thread States Description

NEW A thread that has not yet started is in this state.

RUNNABLE A thread executing in the Java virtual machine is in this state.

BLOCKED A thread that is blocked waiting for a monitor lock is in this state.

WAITING A thread that is waiting indefinitely for another thread to perform


a particular action is in this state.

TIMED_WAITING A thread that is waiting for another thread to perform an action


for up to a specified waiting time is in this state.

TERMINATED A thread that has exited is in this state.

The following diagram shows the different states involved in the life cycle of a thread.
Transitions Between States
o new → start() → runnable
o runnable → scheduler picks → running
o running → wait()/join() → waiting
o running → sleep()/join(timeout) → timed waiting
o running → blocked → when trying to acquire a lock
o any state → finished/error → terminated

Thread Priority in Java


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


Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The [Link]() method returns the


priority of the given thread.

public final void setPriority(int newPriority): The [Link]() 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.
Java Multithreading Example
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
// Override the run method to define the task for the thread
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " - Count: " + i);
try {
// Sleep for a while to simulate some work
[Link](1000);
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
[Link](threadName + " finished.");
}
}
public class Main {
public static void main(String[] args) {
// Create instances of MyThread
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
MyThread thread3 = new MyThread("Thread 3");
// Start the threads
[Link]();
[Link]();
[Link]();
// Wait for all threads to finish
try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("All threads have finished.");
}
}

Advantages of Multithreading in Java


1. Enhanced Performance: Multithreading enables concurrent execution of multiple tasks,
which decreases execution time and boosts efficiency overall.
2. Parallel Execution: Tasks like file processing, network operations, and calculations can
occur simultaneously, enhancing the speed of applications.
3. Improved GUI Responsiveness: For applications with graphical user interfaces (GUIs),
multithreading facilitates smooth interactions by managing user inputs independently
from background tasks.
4. Better CPU Utilization: Threads can operate in parallel, optimizing the use of available
CPU resources, particularly on multi-core processors.
5. Reduced Development Time: Multithreading breaks complex tasks into smaller,
manageable threads, thereby decreasing the effort required for development.

Disadvantages of Multithreading in Java


1. Complexity: Compared to single-threaded systems, multithreaded applications are far
more difficult to write, test, and debug.
2. Resource Overhead: As a result of creating too many threads, performance may suffer
from excessive memory utilization and CPU context switching.
3. Problems with synchronization: Inadequate management of shared resources can result
in issues like race situations, deadlocks, and inconsistent data.
4. Error Handling Difficulties: Errors in one thread may not spread to others easily, making
it more difficult to identify and address problems.
5. Unpredictable Behavior: If threads are not correctly synchronized, the CPU scheduler,
which controls the threads' execution order, might cause unexpected results.

You might also like