0% found this document useful (0 votes)
4 views38 pages

Oopsunit 3

The document provides an overview of threads, multitasking, and multithreading in Java, highlighting their importance for efficient execution and resource utilization. It explains key concepts such as time slicing, context switching, synchronization, and the thread lifecycle, along with the challenges of race conditions and deadlocks. Additionally, it covers GUI components, layout managers, and event handling in Java, emphasizing the use of AWT and Swing for creating user-friendly interfaces.

Uploaded by

notboy0003
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)
4 views38 pages

Oopsunit 3

The document provides an overview of threads, multitasking, and multithreading in Java, highlighting their importance for efficient execution and resource utilization. It explains key concepts such as time slicing, context switching, synchronization, and the thread lifecycle, along with the challenges of race conditions and deadlocks. Additionally, it covers GUI components, layout managers, and event handling in Java, emphasizing the use of AWT and Swing for creating user-friendly interfaces.

Uploaded by

notboy0003
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/ 38

OOPS

unit3
Threads

Threads are lightweight sub processes, representing the smallest unit of


execution with separate paths. The main advantage of multiple threads is
efficiency (allowing multiple things at the same time).
For example, in MS Word, one thread automatically formats the document
while another thread is taking user input. Additionally, multithreading ensures
quick response, as other threads can continue execution even if one gets
stuck, keeping the application responsive.
What is Multitasking?
Multi-tasking is the ability of an operating system to run multiple processes or tasks
concurrently, sharing the same processor and other resources. In multitasking, the
operating system divides the CPU time between multiple tasks, allowing them to
execute simultaneously. Each task is assigned a time slice, or a portion of CPU time,
during which it can execute its code.

Multitasking is when a CPU is provided to execute multiple tasks at a time. Multitasking


involves often CPU switching between tasks so that users can collaborate with each
program together.

A CPU core is a physical processing unit within a CPU (Central Processing Unit) that
performs calculations and executes instructions.The number of cores in a CPU
determines how many tasks it can run at once.
Concurrency vs. Parallelism:
Concurrency: execute alternately (switching between tasks).
Parallelism: execute simultaneously (on multi-core processors).
What is Multithreading?
Multithreading is the ability of a program to execute multiple threads
concurrently, meaning it can perform several tasks seemingly at the same time,
improving performance and resource utilization.

Key Features of Multithreading in Java


•Concurrency: Concurrent execution with multiple threads reduces idle CPU
time.
•Resource Sharing: The reason for threads being able to share the same
memory space is that communication is efficient.
•Independent Execution: Each thread runs independently, so failure in one
thread doesn’t affect others.
•Synchronization Support: Java provides tools to manage thread interference
and memory consistency.
What is Time Slicing in Java Multithreading?
Time Slicing is a CPU scheduling mechanism where the CPU allocates a fixed
time period (or quantum) to each thread before switching to the next thread. This
ensures fair execution among multiple threads in a multitasking environment.

How Time Slicing Works


1. The CPU assigns a small time slice (e.g., a few milliseconds) to each thread.
2. If a thread finishes execution within that time, it releases the CPU.
3. If a thread does not finish, it is paused and placed back in the queue.
4. The CPU switches to the next thread in the queue.
5. This cycle continues, ensuring that no thread monopolizes the CPU.
What is Context Switching in Java Multithreading?
Context Switching is the process of saving the state of a currently running thread
and restoring the state of another thread so that execution can resume from where
it left off. This allows multiple threads to share the CPU efficiently.

How Context Switching Works?


1. The CPU is executing Thread A.
2. The scheduler decides to switch to Thread B.
3. The current state (registers, program counter, variables) of Thread A is saved.
4. The previously saved state of Thread B is restored.
5. Thread B resumes execution from where it last stopped.
6. This process repeats whenever the CPU switches between threads.
1. Extending the Thread Class

run() Method: Contains the


task the thread will execute.
start() Method: Begins the
thread execution by
calling run() internally.
.
2. Implementing the Runnable Interface
Why use Runnable?
It’s more flexible and promotes code
reusability.
Thread Lifecycle

Threads in Java go through the following states:


i. New: Thread is created but not started.
ii. Runnable: Thread is ready to run but waiting for the CPU.
iii. Running: Thread is executing.
iv. Waiting/Blocked: Thread is waiting for resources or another
thread.
v. Terminated: Thread has completed execution.
Synchronization
Synchronization refers to the coordination of multiple processes or threads to
ensure that shared resources are accessed safely and predictably.
Without synchronization, threads can interfere with each other when they share data
or resources (like memory, files, databases, etc.), leading to problems like:
Race conditions
Inconsistent data
Deadlocks or livelocks
Imagine two threads incrementing the same
counter:
These look simple, but under the hood,
counter++ involves:
1. Reading the value of counter
2. Incrementing it
3. Writing it back
Without synchronization, both threads might
read the same value before either writes back —
meaning one update gets lost!
Critical Section
A critical section is the part of code that accesses a shared resource and
must not be executed by more than one thread/process at the same
time.
Rules for Critical Sections:
1. Mutual Exclusion – Only one thread in the critical section at a time
2. Progress – If no thread is in the critical section, others should be able to
enter
3. Bounded Waiting – A thread shouldn't wait forever to enter the critical
section
Race
Condition
A Race Condition occurs
when two or more
concurrent processes (or
threads) access a shared
resource, and the final
outcome depends on the
relative timing of their
execution.
Synchronized keyword

In Java, the synchronized keyword is


used to prevent race conditions
by ensuring that only one thread
at a time can execute a block of
code or method that accesses
shared resources.
It provides mutual exclusion and
helps manage critical sections in
multithreaded programs.
Lock
A lock is a synchronization mechanism that:
Allows only one thread to access a critical section (shared resource) at
a time, while others wait (block) until it is released.
without locks:
Two threads may read/modify/write shared data at the same time.
This leads to race conditions, corrupted data, and unexpected program
behavior.

Locking-
Intrinsic Locking: An intrinsic lock is a built-in locking mechanism provided by every
Java object. It is automatically associated with each object instance and used when
synchronizing critical sections using the synchronized keyword.
Extrinsic Locking: Extrinsic locks in Java, provide manual, explicit control over thread
synchronization. Extrinsic locks are external objects that allow for advanced features and
multiple condition variables for complex thread coordination. They also support fairness
policies, ensuring threads acquire locks in a first-come, first-served manner, reducing
starvation. While offering greater flexibility and control, extrinsic locks require careful
management of lock() and unlock() calls to avoid deadlocks or resource leaks, making
them more complex but powerful for scenarios requiring precise synchronization.
A deadlock happens when two or more threads are waiting for each other
forever, and none of them can continue.
Simple Example:
Thread A locks Resource 1 and waits for Resource 2.
Thread B locks Resource 2 and waits for Resource 1.
Now both threads are stuck, because each is holding something the other
needs — this is a deadlock.

Deadlock needs four conditions:


1. Mutual exclusion – only one thread can use a resource.
2. Hold and wait – holding one resource, waiting for another.
3. No preemption – resources can't be taken by force.
4. Circular wait – a cycle of threads waiting for each other.
Graphical User Interface
(GUI)
A Graphical User Interface (GUI) allows users to interact with software
applications using visual elements like windows, buttons, menus, and icons, rather than
text-based commands (like in a Command-Line Interface).

A GUI provides a visual way to interact with a computer program.


Uses graphical components (buttons, text fields, checkboxes, etc.) instead of typing
commands.
Makes software more user-friendly and accessible.
Introduction to AWT
AWT (Abstract Window Toolkit) is Java's original GUI framework for creating
window-based applications.
•Part of Java’s Foundation Classes (JFC).
•Uses native OS components (heavyweight), meaning buttons, text fields, etc., look
different on Windows, mac OS, and Linux.
•Suitable for simple GUI applications.

Key Features of AWT


✔ Platform-dependent (relies on OS for rendering).
✔ Lightweight compared to Swing/JavaFX.
✔ Event-driven programming (responds to clicks, keypresses).
✔ Contains basic components (buttons, labels, text fields).
AWT Components
Each component typically has 3 key things associated with it:
1. Properties (Attributes)
These define how the component looks or behaves.

2. Events
These are actions that happen on the component (like clicks, typing,
etc.)

3. Event Handlers
These are methods or classes that handle the events and define what
should happen when an event occurs.
Component classes
Component classes in Java are the building blocks used to create graphical user
interfaces (GUIs). These classes are part of the java.awt package and represent different
visual elements like buttons, labels, text fields, and checkboxes.
Each of these elements is called a "component" because it can be placed on a window or
panel.All component classes inherit from the main Component class, which provides basic
features like setting size, color, and position. By using these classes, we can build windows
that users can see and interact with, making Java programs user-friendly and interactive.
Constructor
Method
events
properties
Button
Constructor: Creates a new Button object and sets its label.
Properties: Characteristics of the button (size, color, text, etc.).
Methods: Used to set the properties of the button, like its size, color, and font.
Events: Handles what happens when a user interacts with the button, like clicking it.

In Java, the Container class is a special type of component that can hold other
components (like buttons, labels, text fields, etc.). It's part of the AWT (Abstract
Window Toolkit) and is a subclass of the Component class. Containers are essential in
building complex GUIs because they can group and organize various components.

1. A Container is a special component that can hold other components.


2. Common containers are Frame, Panel, Dialog, etc.
3. Layout managers are used inside containers to organize the components.
4. You add components to containers using the add() method.
In Java, a layout manager is an object that manages the placement and sizing of components
within a container, ensuring a responsive and user-friendly interface. They are essential for
GUI applications as they determine how components are arranged when the window is
resized or when different screen resolutions are used.

Types of Layout Managers


1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. Grid Bag Layout
Border Layout in Java
This layout will display the components along the border of the container. This
layout contains five locations where the component can be displayed. Locations are
North, South, East, west, and Center.The default region is the center.
Flow Layout
This layout will display the components from left to right, from top to bottom. The
components will always be displayed in the first line and if the first line is filled, these
components are displayed on the next line automatically.

Card Layout in Java


A card layout represents a stack of cards displayed on a container. At a time, only one
card can be visible, each containing only one component.
A CardLayout object is a layout manager for a container. It treats each component in
the container as a card. Only one card is visible at a time, and the container acts as a
stack of cards.
Grid Layout in Java
The layout will display the components in the format of rows and columns statically. The
container will be divided into a table of rows and columns. The intersection of a row
and column cell and every cell contains only one component, and all the cells are of
equal size. According to Grid Layout Manager, the grid cannot be empty.

GridBagLayout
GridBagLayout is a flexible layout manager that places components in a grid of
rows and columns, allowing components to span multiple cells and resize
dynamically based on the window size. It arranges components in a grid, but the rows
and columns can have different sizes. It supports alignment, spacing, padding, and resizing
very flexibly.
Swing Package
Swing is a part of Java's standard library used to create Graphical User
Interfaces (GUI).
It builds on AWT (Abstract Window Toolkit) but is more powerful and flexible.

Key Features of Swing:


Lightweight components (drawn by Java, not OS-native)
Pluggable Look and Feel (can change UI appearance)
MVC Architecture (Model-View-Controller)
Event-driven programming
Event Handling
EVENT
Change in the state of an object is known as event i.e. event describes
the change in state of source. Events are generated as result of user
interaction with the graphical user interface components.
For example, clicking on a button, moving the mouse, entering a
character through keyboard , selecting an item from list, scrolling the
page are the activities that causes an event to happen.

An AWT Event in Java is an object that represents a user interaction with a GUI
component.
It tells the program what happened, like:
A button was clicked
A key was pressed
The mouse was moved
•Event is a broad term used across all programming languages and frameworks.
•AWT Event is specific to Java's AWT package and refers to events generated
by AWT components.

EVENT HANDLER
An event handler is the method or block of code that gets executed when an event
occurs.
WHAT IS EVENT HANDLING?
Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism have the code which is known as event handler that is
executed when an event occurs.
The Delegation Event Model is the mechanism Java uses to handle events in GUI
applications (like AWT or Swing).
It is based on the idea of delegating the task of handling an event to a separate object
(called a listener).
Source Listener
A source is the GUI component •A listener is an object that waits for an
(like a button, checkbox, window, etc.) event and handles it.
that generates events .When a user •It is created by implementing a listener
interacts with the component, it creates interface
an event object.This object is then •The listener contains event handler
passed to the registered listener methods that are executed when the event
occurs.

BENEFITS
The event source (UI component) and the event handler (logic) are separated.
Makes the code more modular and easier to maintain.
To handle events, the source must be registered with a listener. Java provides
specific methods for registering listeners based on the type of event.
Java provides a variety of event classes and corresponding listener interfaces.
Below table demonstrates the most commonly used event classes and their
associated
listener interfaces:
Yes, you can call run()
directly, but... It won’t start
a new thread!
A thread-safe class is one that allows multiple
threads to access and modify its data and
methods concurrently without causing data
corruption, race conditions, or unexpected
behavior.

•wait(): The volatile keyword


Pauses a thread's execution, releasing the lock on an ensures that any changes to
object (if the thread was holding it).The thread a volatile variable are
remains in a waiting state until another thread immediately visible to all
calls notify() or notifyAll() on the same object. threads.
•sleep():
Pauses a thread's execution for a specified duration.
The thread remains in a non-runnable state for the
given time.
•notify():
Wakes up one thread that is waiting on the object.
•notifyAll():
Wakes up all threads that are waiting on the object.

You might also like