Tutorial
MutliThreading
www.btechsmartclass.com
Introduction
Every java application runs with the concept of threads or multithreading
Thread is a part of a program which can execute individually
Executing multiple threads simultaneously is
Multithreading
Introduction
What is Multitasking?
It is the ability to perform multiple jobs concurrently. That is
running multiple programs concurrently
Introduction
What is Multithreading?
MS Word Spell Checking
It is referred as multiple threads which are controlled by a single program.
Every program in java can run multiple threads.
Word suggestion in mobile
Playlist in MediaPlayer
Video Games
Types Of
Multitasking
1. Process-based multitasking (Multiprocessing)
2. Thread-based multitasking (Multithreading)
Process-based multitasking Thread-based multitasking
It allows the computer to run two or more programs concurrently It allows the computer to run two or more threads
concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process is a larger unit. Thread is a part of process.
Process is heavy weight. Thread is light weight.
Process requires seperate address space for each. Threads share same address space.
Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.
Inter process communication is expensive. Inter thread communication is not expensive.
Introduction
What is Concurrency?
It is the process of executing multiple processes simultaneously
on a single CPU
What is Parallelism?
It is the process of executing multiple processes simultaneously
on individual CPUs
Thread
Definition: A part of the program which can run individually
public File Downloader(String url) What happens if I want to download 4 File?
{
Code for downloading a file - Execute the program for 4 times
-
-
- Create 4 objects and call the method
return File; one after the other
}
The threads concept makes it easy
Thread
When a java program is executed automatically a thread is
created known as main thread by Java-Runtime system
In java, every thread is created with the help of built-in class
Thread
which is in the
java.lang
package
Use of
Thread
1. Threads are mainly used in server-side
programs where we need to handle multiple
clients on network or internet simultaneously.
2. Threads are used for creating games and
animations.
3. Threads can be used to perform more than
one task simultaneously.
Lifecycle of
Thread
Creating Threads
Thread Class
To understand Multithreading concept we should know the following…
predefined class
creating threads for tasks
methods for controlling threads
What is Parallelism?
Creating
Thread
Create an object of Thread class
Thread t = new Thread( ) ;
Override run() method with the code to be run by that thread
public void run( ){
Code to be run by the
thread
…..
}
Call the run( ) method using start( ) method
t . Start( );