Multithreading Basics & The Lifecycle of a Thread in Java
Overview: A thread waiting for a lock cannot make progress until the lock becomes available.
Basic Idea of Multithreaded Programming
- Before understanding multithreading, let us understand what a Thread is:
- Process (Heavyweight): An independent program currently executing in memory (e.g., MS Word, Chrome, VLC Player).
- Thread (Lightweight Sub-Process): The smallest independent unit of execution within a single process.
- Imagine you are typing an assignment in MS Word:
-
- Thread 1 reads your keyboard strokes and shows letters on screen.
-
- Thread 2 simultaneously checks your spelling and underlines mistakes in red.
-
- Thread 3 auto-saves your document in the background every 60 seconds.
- Because all three threads run concurrently inside one software, MS Word never freezes while checking spelling!
The Main Thread in Java
- Even if you do not create a single thread yourself, every Java program has at least one thread: the
mainthread!
The Lifecycle of a Thread in Java
- During its lifetime, a thread in Java passes through 5 distinct states from its birth (
new) until its death (Terminated). - 1. New (Born State): When a thread object is created using the
newoperator (Thread t = new MyThread();), the thread is said to be in the New state. - At this point, the thread is just an empty object in memory—it is not yet alive, and no system resources or CPU time have been…
- Calling
t.start()moves the thread from New → Runnable. - 2. Runnable (Ready-to-Run State): After
t.start()is invoked, the thread enters the Runnable pool (ready queue). - In this state, the thread is alive and completely ready to run, waiting only for the Thread Scheduler (part of the JVM/OS) to…
- 3. Running State: When the Thread Scheduler selects a thread from the Runnable pool and gives it the CPU, the thread enters the Running state and begins…
- A running thread can voluntarily give up the CPU using
Thread.yield(), or be pre-empted by a higher-priority thread, moving it back to…
View diagram · Figure 3.1: State Transition Diagram — The Lifecycle of a Thread in Java
Important Methods of the Thread Class Controlling the Lifecycle
start(): Allocates a new call stack for the thread, moves it from New → Runnable, and internally invokesrun().run(): Contains the actual task/code that the thread executes when in the Running state.Thread.sleep(long ms): Pauses the currently executing thread formsmilliseconds (throwsInterruptedException).join(): Causes the current thread to wait until the thread on whichjoin()is called terminates.Thread.yield(): Hints to the Thread Scheduler that the current thread is willing to pause and let other threads of equal…isAlive(): Returnstrueif the thread has been started (start()) and has not yet terminated.
Creating Threads, Thread Synchronization & Thread Scheduling
Overview: Calling start creates a separately scheduled thread of execution.
Two Ways to Create a Thread in Java
- Java provides two ways to create and launch a new thread of execution:
- By extending the
Threadclass (class MyThread extends Thread) - By implementing the
Runnableinterface (class MyTask implements Runnable) - Method 1: Extending Thread Class class MyThread extends Thread
- Method 2: Implementing Runnable Interface class MyTask implements Runnable
- Method 1: Creating a Thread by Extending the Thread Class: Create a class that
extends java.lang.Thread. - Override the
public void run()method and write the code you want the thread to execute inside it. - Create an object of your class and call
start()(which creates a new thread call stack and automatically invokesrun()).
View diagram · Figure 3.2: Two Ways of Creating Threads in Java
Thread Synchronization in Java
- When two or more threads try to access and modify a shared resource (such as the same Bank Account balance or Printer object) at the exact…
- Suppose a joint bank account has ₹10,000.
- What is Thread Synchronization?: Thread Synchronization is the mechanism that ensures **only ONE thread can access a shared resource (critical section) at a…
- In Java, every object has an internal lock called a Monitor (or Intrinsic Lock).
- When a method or block is declared with the
synchronizedkeyword, a thread must first acquire the object’s Monitor Lock before…
Thread Scheduling and Thread Priority
- When multiple threads are waiting in the Runnable queue, who decides which thread gets the CPU next?
- Preemptive-Priority Scheduling: The thread with the highest priority number is chosen to run first.
- Time-Slicing (Round-Robin): If multiple threads have the exact same priority, each thread is given a fixed slice of CPU time in turn.
- Thread Priorities in Java (1 to 10): Every thread in Java is assigned an integer priority between
1(Lowest) and10(Highest). Thread.MIN_PRIORITY=1(Lowest priority)Thread.NORM_PRIORITY=5(Default normal priority)Thread.MAX_PRIORITY=10(Highest priority)- Methods to Get and Set Thread Priority:
int getPriority(): Returns the thread’s current priority.
Exception Handling in Java: try, catch, finally, throw & throws
Overview: A method can throw one exception object when a file is missing.
Basic Idea of Exception Handling
- What is an Exception? An Exception is an abnormal condition or unexpected runtime event (such as dividing a number by zero, accessing an…
- What happens if an Exception is NOT handled? The JVM immediately aborts (crashes) the program at that line, prints an ugly technical stack trace, and **none of the…
- What is Exception Handling? It is a powerful mechanism to catch runtime errors gracefully, display a user-friendly message, and **allow the rest of the…
Exception Hierarchy & Checked vs Unchecked Exceptions
- In Java,
java.lang.Throwableis the root superclass of all errors and exceptions. - 1. Direct Superclass: Subclasses of
Exception(excludingRuntimeException). - 2. Checked By Compiler?: Yes! Code will not even compile unless you handle them with
try-catchor declare them withthrows. - 3. Common Examples:
IOException,FileNotFoundException,SQLException,ClassNotFoundException.
View diagram · Figure 3.3: The Exception Hierarchy in Java (java.lang.Throwable)
The 5 Keywords of Java Exception Handling
- Java exception handling is managed using 5 keywords:
try,catch,finally,throw, andthrows. - 1. The try Block: Encloses the risky statements that might throw an exception at runtime.
- A
tryblock cannot stand alone—it must be followed by at least onecatchblock or afinallyblock. - 2. The catch Block: Placed immediately after the
tryblock to catch and handle the exception object thrown by thetryblock. - Multiple
catchBlocks: A singletryblock can be followed by multiplecatchblocks to handle different types of exceptions specifically (Rule:… - 3. The finally Block: An optional block placed after
try-catchthat is guaranteed to execute whether an exception occurs or not! - Why use
finally? Used for cleanup code such as closing open files (file.close()), closing JDBC database connections (conn.close()),…
View diagram · Figure 3.4: Execution Flow of try - catch - finally Block
throw vs throws Keyword in Java
- This is the #1 most asked question from Exception Handling in DAVV BCA exams!
- A. The throw Keyword (Explicitly Throwing an Exception): Used inside a method body to explicitly create and throw a single exception object (especially for custom validation rules like…
- Syntax:
throw new ArithmeticException("Insufficient Balance"); - B. The throws Keyword (Declaring Possible Exceptions): Used in the method signature (header) to warn the caller of the method that this method might throw one or more **Checked…
- Syntax: `void readFile() throws IOException, SQLException { …
- 1. Purpose: Used to explicitly throw an exception object from a method or block.
- 2. Where Used?: Used inside the method body.
- 3. Followed By: Followed by a single object instance (
throw new Exception();).
The AWT: Class Hierarchy of Window Fundamentals, Frame & UI Components
Overview: A Frame gives a registration form its top-level window.
Introduction to AWT (Abstract Window Toolkit)
- AWT (
java.awtpackage) is Java’s original platform-dependent toolkit for creating GUI (Graphical User Interface) window-based… - Why are AWT components called “Heavyweight”? Because AWT components rely directly on the host Operating System’s native GUI widgets (OS peers).
The Class Hierarchy of Window Fundamentals
- Understanding the AWT Class Hierarchy is essential for DAVV exams.
- Key Window Fundamental Classes Explained:
Component: The abstract superclass of every non-menu user interface element (Button,Label,Checkbox, etc.). Container: A subclass ofComponentthat can hold other components inside it using theadd(Component c)method and arrange…Window: A top-level container that sits directly on the desktop without any border or menu bar (rarely used directly).Panel: The simplest concrete subclass ofContainer.Frame: A subclass ofWindowthat represents a standard desktop application window complete with a **Title Bar, Resizable…
View diagram · Figure 3.5: The AWT Class Hierarchy of Window Fundamentals (java.awt)
Creating a Frame Window in AWT
- You can create a GUI window in AWT by extending
Frame(or creating an instance ofFrame) and using three essential methods: setTitle(String title): Sets the text in the window’s title bar.setSize(int width, int height): Sets the width and height of the window in pixels.setVisible(true): Makes the frame visible on the screen (by default, frames are invisible!).
Basic AWT User Interface Components
- All AWT UI components are added to a
FrameorPanelusing theadd(componentObj)method. - 1. Label (Read-Only Text): Displays a single line of uneditable text (used as a caption next to text fields).
- Constructors:
Label(),Label(String text),Label(String text, int alignment)(Label.LEFT,Label.CENTER,Label.RIGHT). - Example:
Label lblName = new Label("Student Name:"); - 2. Button (Clickable Push Button): Creates a labeled push button that triggers an
ActionEventwhen clicked. - Constructors:
Button(),Button(String label) - Example:
Button btnSubmit = new Button("Submit Form"); - 3. Checkbox (Multiple Selection Tick Box): A box that can be either checked (
true) or unchecked (false).
AWT Layout Managers: FlowLayout, GridLayout, BorderLayout & CardLayout
Overview: FlowLayout places buttons one after another and can wrap them.
What is a Layout Manager in AWT?
- When you add buttons, labels, and text fields to a
FrameorPanel, instead of manually calculating pixel coordinates(x, y, width, height)… - We set a container’s layout manager using the
setLayout(LayoutManager mgr)method: - 2. BorderLayout Divides container into 5 zones: NORTH, SOUTH, EAST, WEST, CENTER (Default for Frame)
- 3. GridLayout Divides container into a rectangular matrix of equal-sized cells (Rows × Columns)
- 4. CardLayout Stacks components one behind another like a deck of playing cards (Only 1 visible at a time)
View diagram · Figure 3.6: The 4 Standard AWT Layout Managers in Your Syllabus
FlowLayout (Left-to-Right Row Arrangement)
- How it works:
FlowLayoutis the simplest layout manager. - Default Layout For:
PanelandApplet. - Alignment Constants:
FlowLayout.LEFT,FlowLayout.CENTER(default),FlowLayout.RIGHT. - Constructors of FlowLayout:
FlowLayout()— Centers components with a default 5-pixel horizontal and vertical gap. FlowLayout(int align)— Specifies alignment (LEFT,CENTER, orRIGHT).FlowLayout(int align, int hgap, int vgap)— Specifies alignment and custom pixel gaps.
BorderLayout (5 Geographic Regions)
- How it works:
BorderLayoutdivides the container into 5 distinct regions:NORTH(Top),SOUTH(Bottom),EAST… - Default Layout For:
Frame,Window, andDialog. - Important Rule: Each region can hold only ONE component (to put multiple buttons in the
SOUTHregion, put them inside aPanelfirst,…
View diagram · Figure 3.7: The 5 Regions of BorderLayout
GridLayout (Equal-Sized Rows × Columns Matrix)
- How it works:
GridLayoutdivides the container into a 2D grid (table) of rows and columns. - Key Characteristic: Every cell in a
GridLayoutis forced to be of the exact same width and height, and each component stretches to… - Constructors of GridLayout:
GridLayout(int rows, int cols)— Creates a grid with specified rows and columns. GridLayout(int rows, int cols, int hgap, int vgap)— Adds horizontal and vertical spacing between cells.
CardLayout (Stack of Cards — Wizard / Tab View)
- How it works:
CardLayouttreats each component (usually aPanel) as a card in a deck of playing cards stacked one on top of… - Key Characteristic: Only ONE card (panel) is visible on screen at any given time! You can flip between cards using built-in navigation…
- Important Navigation Methods of CardLayout:
first(Container parent): Flips to the very first card in the deck. next(Container parent): Flips to the next card.previous(Container parent): Flips to the previous card.last(Container parent): Flips to the last card.show(Container parent, String cardName): Jumps directly to a specific card by its name!
Quick Summary Table of All 4 Layout Managers
FlowLayout: Left-to-right row by row; wraps when full.BorderLayout: 5 regions:NORTH,SOUTH,EAST,WEST,CENTER.GridLayout: Rectangular matrix ofrows × cols.CardLayout: Stacked one behind another; only 1 visible at a time.