Chapter 5 - Java MultiThreading
Chapter 5 - Java MultiThreading
Java Multithreading
By: Sinodos G.
1
Multitasking
What is multitasking ?
• Multithreading
3
Multiprocessing
What is Multiprocessing?
Figure 1: game
• Games are best example for applying Multithreading
7
Cont’d …
Multiprocessing and multithreading, both are used to
achieve multitasking.
But we can use multithreading than multiprocessing
because threads are:-
• Share a common memory area.
• They don't allocate separate memory area so saves
memory, and
• takes less time than process.
• mostly used in games, animation etc.
8
Thread
The smallest unit of executable code that performs a
particular task.
• An application can be divided into multiple tasks and
each task can be assigned to a thread.
9
Cont’d …
Main Thread
When Java programs execute, there is always one
thread running and that is the main thread.
Itis this thread from which child threads are
created.
Program is terminated when main thread stops
execution.
can be controlled through Thread objects.
Reference of the main thread can be obtained by
calling the currentThread() method of the Thread
class.
10
Cont’d …
It is an independent path of execution in a program.
11
Cont’d …
Why java is secured and high performed Language?
A Java program can have any number of associated
threads that are created explicitly.
• if a program has more than one associated thread, it
is said to be multithreaded.
12
Cont’d …
Advantages of Multithreading
Threads are independent and it can perform multiple
operations at same time.
Perform many operations together so it saves time.
Threads are independent so it doesn't affect other
threads if exception occur in a single thread.
13
Cont’d …
Increases performance of single-processor system
Encourages faster execution of a program
Introduces the concept of parallel processing
Disadvantage
• Complex debugging and testing processes
• Overhead switching of context
• Increased potential for deadlock occurrence
• Increased difficulty level in writing a program
• Unpredictable results
14
Creating Threads
15
Life Cycle of a Thread
16
Cont’d …
17
Cont’d …
B. Runnable: a thread after invocation of start () method,
but the thread scheduler has not selected it to be the
running thread.
18
How to create Thread
There are two ways to create a thread in java. These
are by:-
Extending Thread class
Declare a class that is a sub-class of the class Thread
defined in java.lang package.
class mythread extends Thread
Output:
21
Cont’d …
Thread()
Thread(String name)
Thread(Runnable r)
22
Cont’d …
Commonly used methods of Thread class
run():- is used to perform action for a thread.
start(): starts the execution of the thread. JVM
calls the run () method on the thread.
24
Starting a thread
Start () method of Thread class is used to start a
newly created thread. It performs the following
tasks:
25
Cont’d …
After a new thread has been initiated, we use the start()
method to start the thread.
Otherwise it is an empty Thread object with no system
resources allocated.
Preemptive scheduling:
The highest priority task executes until it enters the
waiting or dead states or a
higher priority task comes into existence.
27
Cont’d …
Time slicing:
A task executes for a predefined slice of time
and then reenters the pool of ready tasks.
28
Thread - sleep()
A method used to tell the current thread to sleep for certain
time.
Sleep method accepts time in milliseconds.
Can throw InterruptedException.
Cannot guarantee that a thread goes to sleep for specified
time.
Once sleep state is complete, the thread can move to
Runnable or Running state.
At a time only one thread is executed.
If you sleep a thread for the specified time, the thread
scheduler picks up another thread.
29
Example: of sleep method
30
Daemon Thread
• There are Two types of threads in Java:
User threads:
– Created by the user
Daemon threads:
– Threads that work in the background providing
service to other threads
(e.g. – the garbage collector thread)
31
Cont’d …
• When user thread exits, JVM checks to find out if any
other thread is running.
• If there are, it will schedule the next thread.
32
The join () method
Waits for a thread to die.
The calling thread waits until the specified thread
terminates.
34
Priority of a Thread
Determine the order in which threads are scheduled.
There are three thread priority class defined. These are:
MIN_PRIORITY
NORM_PRIORITY
MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
Threads with higher priority are more important to a program
and should be allocated processor time before lower-priority
threads.
However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent.
.35
Example:
36
Synchronization
What happens if two threads have access to the same
object and each calls a method that modifies the state of
the object?
37
Cont’d …
When two or more thread used a shared resources that lead
to two kind of errors. These are:-
• Thread interference and
• Memory consistency error
To avoid this error you need to use a synchronized object
that the resource will be used by one thread at a time and
the process by which synchronization is achieved is called
synchronization.
The general form of synchronized is as follows. Syntax
synchronized (object)
{
statement;
}
38
Cont’d …
Synchronization is done with a lock on object means
every object has a lock and if a thread need to access
that object field have to acquire the lock before access
them and release the lock when done.
Reading Assignment
• Read more about Synchronization
39
Question ?
END
40