Multithreading With Examples
Multithreading With Examples
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.
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
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.
•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
Method Use
Output:
Enumerations
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: