0% found this document useful (0 votes)
4 views

Multithreading With Examples

The document covers multithreading and multitasking in Java, explaining key concepts such as thread life cycle, thread priorities, synchronization, inter-thread communication, and the use of enums, autoboxing, annotations, and generics. It highlights the differences between multithreading and multitasking, along with examples and code snippets for better understanding. Additionally, it discusses thread groups and daemon threads, illustrating their functionalities and applications.

Uploaded by

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

Multithreading With Examples

The document covers multithreading and multitasking in Java, explaining key concepts such as thread life cycle, thread priorities, synchronization, inter-thread communication, and the use of enums, autoboxing, annotations, and generics. It highlights the differences between multithreading and multitasking, along with examples and code snippets for better understanding. Additionally, it discusses thread groups and daemon threads, illustrating their functionalities and applications.

Uploaded by

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

Multithreading &

Multitasking
Agenda
+ Multithreading + Enumerations
+ Multitasking + Auto boxing
+ Thread life cycle + Annotation
+ Thread priorities + Generics
+ Thread group
+ Thread
synchronization
+ Daemon thread
+ Inter-thread
communication

M U LT I T H R E A D I N G A N D M U LT I T A S K I N G 2
MULTITHREADING
Multithreading is the process of executing two or more threads
simultaneously within a single program to achieve concurrent
execution.

 Each thread is a lightweight subprocess.

 Threads share the same memory space, making


communication easier and faster.

 Java supports multithreading through the Thread class and


the Runnable interface.
 Threads can run in parallel, especially on multi-core
processors.
M U LT I T H R E A D I N G A N D M U LT I T A S K I N G 3
EXAMPLE

class MyThread extends Thread {


public void run() {
System.out.println("Thread is
running...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread
}
}
MULTITASKING

Multitasking is the ability of an operating system or a program to perform


multiple tasks (processes) at the same time.
In Java, multitasking can be achieved in two main ways:
Process-based multitasking
➤ Executing multiple programs at the same time.
Example: Running a Java compiler and a media player simultaneously.

Thread-based multitasking
➤ Running multiple threads within a single Java program.
Example: A text editor doing spell check, autosave, and typing input at
once.
Eg: listening song and typing words in a file at same time.

M U LT I T H R E A D I N G A N D M U LT I T A S K I N G 5
DIFFRENCE
FEATURE MULTITHREADING MULTITASKING
Executing multiple threads within a Executing multiple tasks/processes at
Definition
single process the same time

Memory Threads share memory Processes have separate memory

Execution Runs in a single program, concurrently Runs multiple programs simultaneously

Communication Easier (shared memory space) Difficult (separate memory spaces)


Speed Faster (less context switching) Slower than multithreading
Using MS Word while downloading a
Example Media player: play audio + show lyrics
file
Depends on OS-level process
Java Support Java provides built-in support
management

6
Thread life The thread life cycle describes the different states a thread goes through, from creation
to termination, including New, Runnable, Blocked, Waiting and Terminated.

cycle Here's a breakdown of each state:


•New:
A thread is in this state when it's created but hasn't started execution yet.
•Runnable:
After calling the start() method, the thread enters the runnable state, meaning it's ready
to run and waiting for the CPU to allocate resources.
•Blocked:
A thread is blocked when it's waiting to acquire a lock or resource, or is waiting for an
event to occur.

•Waiting:
A thread enters the waiting state when it's waiting for another thread to perform a
specific action or for a certain condition to be met.

•Terminated:
The thread has completed its execution, either by returning normally from
the run() method or by throwing an uncaught exception, and is no longer alive.

M U LT I T H R E A D I N G A N D M U LT I T A S K I N G 7
Thread Priorities in Java

• Thread priority tells the Java system how important a thread


is compared to others.
• When many threads are ready to run, the Java thread
scheduler may give preference to higher-priority threads.
• Thread priority range: Priority values between 1 to 10.
Thread Priority
Constants:
Priority Level Value Meaning
Thread.MIN_PRIORITY 1 Lowest priority
Thread.NORM_PRIORITY 5 Default priority
Thread.MAX_PRIORITY 10 Highest priority

How to Set Thread Priority in Java

You can use the .setPriority(int value) method to set a thread’s


priority.
Code
:
class MyThread extends Thread {
public void run() {
LowPriority (MIN = 1) - Priority: 1
NormalPriority (NORM = 5) - Priority: 5
System.out.println(getName() + " - Priority: " + getPriority()); HighPriority (MAX = 10) - Priority: 10
}} CustomPriority (3) - Priority: 3
public class ThreadPriorityExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
MyThread t4 = new MyThread();
// Set thread names
t1.setName("LowPriority (MIN = 1)");
t2.setName("NormalPriority (NORM = 5)");
t3.setName("HighPriority (MAX = 10)");
t4.setName("CustomPriority (3)");
// Set priorities
t1.setPriority(Thread.MIN_PRIORITY); // priority = 1
t2.setPriority(Thread.NORM_PRIORITY); // priority = 5
t3.setPriority(Thread.MAX_PRIORITY); // priority = 10
t4.setPriority(3); // custom priority = 3
// Start all threads
t1.start();
t2.start();
t3.start();
t4.start();
}}
Output:
Thread Synchronization

• Thread synchronization is the coordination between threads


to ensure that they don't interfere with each other.
• In multithreading, multiple threads may try to access shared
resources simultaneously, leading to data inconsistency or
errors.
• Synchronization ensures that only one thread can access a
resource at a time, thus avoiding conflicts.
How to Synchronize Threads in
Java
•Use the synchronized keyword to control access to critical sections
of code.
•The synchronized keyword ensures that only one thread can
access a method or block of code at any given time.
Code:
class Counter { try {
private int count = 0; t1.join();
public synchronized void increment() { t2.join();
count++; t3.join();
} } catch (InterruptedException e) {
public int getCount() { e.printStackTrace(); }
return count; }} System.out.println("Final counter value: " + counter.getCount());}}
class MyThread extends Thread {
private Counter counter;
public MyThread(Counter counter) {
this.counter = counter; }
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment(); // Increment counter 1000 times
} }}
public class SynchronizationExample {
public static void main(String[] args) {
Counter counter = new Counter();
MyThread t1 = new MyThread(counter);
MyThread t2 = new MyThread(counter);
MyThread t3 = new MyThread(counter);
t1.start();
t2.start();
t3.start(); Output:
// Wait for threads to finish Final counter value: 3000
Inter-thread
Communication
• It allows multiple threads to coordinate with each other.
One thread waits, while another notifies it when a task is done.
Avoids busy waiting (looping and checking).

Key Methods (used in synchronized blocks)

Method Use

wait() Makes the current thread wait


notify() Wakes up one waiting thread
notifyAll() Wakes up all waiting threads
Code:
class Shared { public static void main(String[] args) {
boolean flag = false; Shared shared = new Shared();
synchronized void sayHi() { SecondThread t2 = new SecondThread(shared); // Say "Hello"
System.out.println("Hi"); (waits)
flag = true; FirstThread t1 = new FirstThread(shared); // Say "Hi"
notify(); // Wake up the other thread } (notifies)
synchronized void sayHello() { t2.start();
while (!flag) { t1.start(); Output:
try { wait(); } catch (Exception e) {} }} Hi
} Hello
System.out.println("Hello");}}
class FirstThread extends Thread {
Shared shared;
FirstThread(Shared shared) {
this.shared = shared;}
public void run() {
shared.sayHi();
}}
class SecondThread extends Thread {
Shared shared;
SecondThread(Shared shared) {
this.shared = shared;}
public void run() {
shared.sayHello();}}
public class SimpleCommunication {
Thread group

• A Thread Group is a way to group multiple threads together


in Java.It helps you manage multiple threads as a unit, like:
• Checking active threads,
• Interrupting all threads in a group,
• Organizing threads by task.
Code:
class MyThread extends Thread { Output:
MyThread(ThreadGroup group, String name) { Running thread: Thread-1
super(group, name); Running thread: Thread-2
} Thread group name: MyGroup
public void run() { Active threads: 2
System.out.println("Running thread: " +
Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Thread interrupted: " + getName());
}}}
public class ThreadGroupExample {
public static void main(String[] args) {
// Create a thread group
ThreadGroup group = new ThreadGroup("MyGroup");
// Create threads in the group
MyThread t1 = new MyThread(group, "Thread-1");
MyThread t2 = new MyThread(group, "Thread-2");
t1.start();
t2.start();
// Show group info
System.out.println("Thread group name: " + group.getName());
System.out.println("Active threads: " + group.activeCount());
}}
Daemon
thread
A Daemon Thread is a background thread that runs in support of user threads.
📝 When all user threads finish, the JVM exits and daemon threads are killed
automatically.

Examples of Daemon Threads in Real


Life:
•Garbage Collector
•Auto-save feature
•Background tasks
Code:

class AutoSave extends Thread { User is working... (1)


public void run() { Auto-saving your work...
while (true) { User is working... (2)
System.out.println("Auto-saving your work...");
try {
User is working... (3)
Thread.sleep(2000); // Wait for 2 seconds before next save Auto-saving your work...
} catch (InterruptedException e) { User is working... (4)
System.out.println("Auto-save interrupted"); User is working... (5)
} }}} User has finished working. Program ends.
public class AutoSaveExample {
public static void main(String[] args) {
AutoSave autoSaveThread = new AutoSave
autoSaveThread.setDaemon(true); autoSaveThread.start(); //
Start the thread
for (int i = 1; i <= 5; i++) {
System.out.println("User is working... (" + i + ")");
try {
Thread.sleep(1000); // Simulate work for 1 second
} catch (InterruptedException e) {
System.out.println("Main thread interrupted"); }}
System.out.println("User has finished working. Program ends.");}}

Output:
Enumerations

An Enum (short for enumeration) is a special Java type used to define a


collection of constants. Enums are typically used to represent fixed sets
of related values like:
• Days of the week,
• Seasons,
• Directions (NORTH, SOUTH, etc.)
Enums are more powerful than simple constants and can have methods,
fields, and constructors.
Code
:enum TrafficLight { }
RED, GREEN, YELLOW Output:
} Stop!

public class EnumExample {


public static void main(String[] args) {
TrafficLight signal = TrafficLight.RED;

switch (signal) {
case RED:
System.out.println("Stop!");
break;
case GREEN:
System.out.println("Go!");
break;
case YELLOW:
System.out.println("Slow down!");
break;
}
}
Auto boxing
Autoboxing is the automatic conversion between primitive types (like int,
char, double) and their corresponding wrapper classes (like Integer,
Character, Double).

For example:
•An int can be automatically converted to an Integer.
•A char can be automatically converted to a Character.
Autoboxing makes code cleaner and easier to read because Java
automatically handles these conversions.
Code:

public class AutoboxingExample


public static void main(String[] args) {
int num = 10; // primitive int
Integer obj = num; // autoboxing: int -> Integer
System.out.println("Primitive: " + num);
System.out.println("Object: " + obj);
}
} Output:
Primitive: 10
Object: 10
Annotation

An Annotation is a special kind of metadata in Java. It


provides additional information about the code but does not
directly affect the logic of the program. Annotations are used to
provide metadata (data about data) to the compiler, runtime, or
other tools.
Example:
@Override
Generics

Generics in Java allow you to write code that works with


different types in a safe and flexible way. Generics allow
you to write classes, methods, or interfaces that can handle
any type of data but still maintain type safety.
This helps prevent errors like trying to add the wrong type of
object to a collection or container.
Code:
class Box<T> { // <T> is a placeholder for any type. 10
private T value; Hello
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
public class Main {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.setValue(10); // Only accepts Integers
Integer value = intBox.getValue(); // No need for casting
System.out.println(value);
Box<String> strBox = new Box<>();
strBox.setValue("Hello"); // Only accepts Strings
String strValue = strBox.getValue(); // No need for casting
System.out.println(strValue);
}
}
Output:
Thank You
M U LT I T H R E A D I N G A N D M U LT I T A S K I N G 27

You might also like