Chapter 5 - Java MultiThreading

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Chapter Five

Java Multithreading

By: Sinodos G.

1
Multitasking
 What is multitasking ?

• It is a process of executing multiple tasks


simultaneously and used to utilize the CPU.
• Handling multiple tasks – Multitasking
2
Cont’d …
 An art of handling different (more than one) tasks
simultaneously at a given point of time.
 Sometimes it is also called as multi-processing.
 In Computer it refers, when multiple processes share
common processing resources such as a CPU.
 It can be achieved by two ways. These are:-
• Multiprocessing

• Multithreading

3
Multiprocessing
 What is Multiprocessing?

 Each process have its own address in memory


 Process is heavyweight.
 Cost of communication b/n the processes is high.
 Switching from one process to another require some time
for saving and loading registers, memory maps, updating
lists etc.
4
Cont’d …
 Multi-threading
• A programmable approach to achieve multi-tasking.
Where each thread holds control of one program. A
thread is a single line of control

• Example: a Team leader in a team, who assigns individual


tasks for the team members and he have control on each
task status, which is nothing but a thread.
5
Cont’d …
 Ability to initiate multiple processes Multithreading

• Spell Checker in word can be considered as a thread

• An application running is called a process, a process can


have multiple threads.
6
Cont’d …

Figure 1: game
• Games are best example for applying Multithreading

• A program that implicitly use just one thread is


described as single threaded.
• enables you to write in a way where multiple activities
can proceed concurrently in the same program.

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.

 Many threads executing simultaneously is termed as


Multithreading.
• Appears that the processes are running concurrently,

but it isn’t so.


A lightweight sub process, a smallest unit of processing.
 Threads are independent, if there occurs exception in
one thread, it doesn't affect other threads.

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.

 Threads are scheduled by OS to be processed by the


Processor, so its behavior depends on the OS.
 It cannot be guaranteed about threads execution.

 Java provides the java.lang.Thread class for explicitly


creating and controlling threads.
 To use threads, first create a subclass of Thread.

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.

 Threads share the same address space.


 Thread is lightweight.
 Cost of communication between the thread is low.
 At least one process is required for each thread.

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

 A thread can be in one of the five states.

 The life cycle of the thread in java is controlled by


JVM.

 The java thread states are as follows. These are:


• New
• Runnable
• Running
• Blocked(waiting)
• Terminate (dead)

16
Cont’d …

Figure 2: Thread life cycle

A. New: create an instance of Thread class but before


the invocation of start () method.

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.

C. Running: The thread is in running state if the thread


scheduler has selected it.

D. Waiting (Blocked): This is the state when the thread is


still alive, but is currently not eligible to run.

E. Terminated: A thread is in terminated or dead state


when its run () method exits.

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

 Implementing Runnable interface


 Declare a class that implements the Runnable interface
(recommended).

 class mythread implements Runnable


19
Example1: Java Thread by extending Thread class

Output: The thread is running . . .


20
Example2: a Thread by implementing Runnable interface

Output:

21
Cont’d …

 Commonly used Constructors of Thread class

 Thread()

 Thread(String name)

 Thread(Runnable r)

 Thread(Runnable r, String name)

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.

 sleep(): Causes the currently executing thread to


sleep for the specified number of milliseconds.

 join(): waits for a thread to die.


 String getName(): returns the name of the
thread.
23
Cont’d …
 setName(String name): changes the name of the
thread.
 int getId(): returns the id of the thread.
 Thread.State getState(): returns the state of the thread.
 boolean isAlive(): tests if the thread is alive.
 resume(): is used to resume the suspended thread.
 stop(): is used to stop the thread.
 interrupt(): interrupts the thread.

24
Starting a thread
 Start () method of Thread class is used to start a
newly created thread. It performs the following
tasks:

 A new thread starts.

 The thread moves from new state to the


Runnable state.

 When the thread gets a chance to execute, its


target run () method will run.

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.

• When start() method is invoked, the system resources


required to run the thread is created and schedules the
thread to run.
• It then calls the thread’s run() method.
26
Cont’d …
 Thread Scheduler in Java
 decides which thread should run.

 Only one thread at a time can run in a single process.


 The thread scheduler mainly uses preemptive or time
slicing scheduling to schedule the threads.

 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.

 The scheduler then determines which task


should execute next, based on priority and
other factors.

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.

• If the only executing threads are daemon threads,


it exits.
• We can set a thread to be a Daemon if we do not want
the main program to wait until a thread ends.
– isDaemon(), setDaemon(true)

32
The join () method
 Waits for a thread to die.
 The calling thread waits until the specified thread
terminates.

 It causes the currently running threads to stop


executing until the thread it joins with completes its
task.

 Allows specifying the maximum amount of time that


the program should wait for the particular thread to
terminate.

 It throws InterruptedException if another thread


interrupts it.
33
Example: of join() method

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?

 In such a case, data may become inconsistent.

 Situation is often called a race condition.

 To avoid simultaneous access of a shared object by


multiple threads, you must learn how to synchronize the
access.

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.

 A method is synchronized using synchronized keyword.

Reading Assignment
• Read more about Synchronization

39
Question ?

END
40

You might also like