SlideShare a Scribd company logo
Multithreading
2
A Single Threaded Program
class ABC
{
….
public void main(..)
{
…
..
}
}
begin
body
end
3
Multithreaded Programming
 Java provides built-in support for
multithreaded programming.
 A multithreaded program contains two or more
parts that can run concurrently.
 Each part of such a program is called a thread,
and each thread defines a separate path of
execution.
 Thus, multithreading is a specialized form of
multitasking.
4
A Multithreaded Program
Main Thread
Thread A Thread B Thread C
start start
start
Threads may switch or exchange data/results
5
Single and Multithreaded Processes
Threads are light-weight processes within a process
Single-threaded Process
Single instruction stream Multiple instruction stream
Multiplethreaded Process
Threads of
Execution
Common
Address Space
6
Multitasking
 There are two distinct types of multitasking:
 process-based and
 thread-based
 It is important to understand the difference
between the two.
 For many users, process-based multitasking is the
more familiar form.
 A process is, in essence, a program that is
executing.
 Thus, process-based multitasking is the feature
that allows your computer to run two or more
programs concurrently.
7
Process-based Multitasking
 For example, process-based multitasking
enables you to run the Java compiler at the
same time that you are using a text editor or
visiting a web site.
 In process-based multitasking, a program is the
smallest unit of code that can be dispatched by
the scheduler.
8
Thread-based Multitasking
 In a thread-based multitasking environment, the
thread is the smallest unit of dispatchable code.
 This means that a single program can perform two
or more tasks simultaneously.
 For instance, a text editor can format text at the
same time that it is printing, as long as these two
 actions are being performed by two separate
threads.
 Thus, process-based multitasking deals with the
“big picture,” and thread-based multitasking
handles the details.
9
Multitasking
 Multitasking threads require less overhead
than multitasking processes.
 Processes are heavyweight tasks that require
their own separate address spaces.
 Interprocess communication is expensive and
limited.
 Context switching from one process to another
is also costly.
10
Multitasking
 Threads, on the other hand, are lighter weight.
 They share the same address space and
cooperatively share the same heavyweight
process.
 Interthread communication is inexpensive, and
context switching from one thread to the next
is lower in cost.
 While Java programs make use of process-
based multitasking environments, process-
based multitasking is not under Java’s control.
11
Multithreaded Server
 For Serving Multiple Clients Concurrently
Server
Threads
Server ProcessClient 1 Process
Client 2 Process
Internet
12
Web/Internet Applications
 Serving Many Users Simultaneously
Internet
Server
PC client
Local Area Network
PDA
13
Multithreaded/Parallel File Copy
reader()
{
- - - - - - - - -
-
lock(buff[i]);
read(src,buff[i]);
unlock(buff[i]);
- - - - - - - - -
-
}
writer()
{
- - - - - - - - - -
lock(buff[i]);
write(src,buff[i]);
unlock(buff[i]);
- - - - - - - - - -
}
buff[0]
buff[1]
Cooperative Parallel Synchronized
Threads
14
Levels of Parallelism
x LoadCPU
Code-Granularity
Code Item
Large grain
(task level)
Program
Medium grain
(control level)
Function (thread)
Fine grain
(data level)
Loop (Compiler)
Very fine grain
(multiple issue)
With hardware
Task i-l Task i Task i+1
func1 ( )
{
....
....
}
func2 ( )
{
....
....
}
func3 ( )
{
....
....
}
a ( 0 ) =..
b ( 0 ) =..
a ( 1 )=..
b ( 1 )=..
a ( 2 )=..
b ( 2 )=..
+
Sockets/
PVM/MPI
Threads
Compilers
15
What are Threads?
 A piece of code that run in concurrent with
other threads.
 Each thread is a statically ordered sequence of
instructions.
 Threads are being extensively used express
concurrency on both single and
multiprocessors machines.
 Programming a task having multiple threads of
control – Multithreading or Multithreaded
Programming.
16
Thread Priorities
 Java assigns to each thread a priority that
determines how that thread should be treated
with respect to the others.
 Thread priorities are integers that specify the
relative priority of one thread to another.
 As an absolute value, a priority is meaningless;
a higher-priority thread doesn’t run any faster
than a lower-priority thread if it is the only
thread running.
17
Context Switch
 Instead, a thread’s priority is used to decide when
to switch from one running thread to the next.
 This is called a context switch. The rules that
determine when a context switch takes place are
simple:
 A thread can voluntarily relinquish control. This is done
by explicitly yielding, sleeping, or blocking on pending
I/O. In this scenario, all other threads are examined,
and the highest-priority thread that is ready to run is
given the CPU.
 A thread can be preempted by a higher-priority
thread. In this case, a lower-priority thread that does
not yield the processor is simply preempted-no matter
what it is doing-by a higher-priority thread. Basically, as
soon as a higher-priority thread wants to run, it does.
This is called preemptive multitasking.
18
Synchronization
 Because multithreading introduces an
asynchronous behavior to your programs, there
must be a way for you to enforce synchronicity
when you need it.
 For example, if you want two threads to
communicate and share a complicated data
structure, such as a linked list, you need some
way to ensure that they don’t conflict with
each other.
 That is, you must prevent one thread from
writing data while another thread is in the
middle of reading it.
19
Synchronization
 For this purpose, Java implements an elegant twist
on an age-old model of interprocess
synchronization: the monitor.
 In Java, there is no class “Monitor”; instead, each
object has its own implicit monitor that is
automatically entered when one of the object’s
synchronized methods is called.
 Once a thread is inside a synchronized method, no
other thread can call any other synchronized
method on the same object.
 This enables you to write very clear and concise
multithreaded code, because synchronization
support is built into the language.
20
Messaging
 After we divide our program into separate threads,
we need to define how they will communicate with
each other.
 When programming with some other languages, we
must depend on the operating system to establish
communication between threads.
 This, of course, adds overhead.
 By contrast, Java provides a clean, low-cost way
for two or more threads to talk to each other, via
calls to predefined methods that all objects have.
 Java’s messaging system allows a thread to enter a
synchronized method on an object, and then wait
there until some other thread explicitly notifies it
to come out.
21
The Thread Class and the Runnable
Interface
 Java’s multithreading system is built upon the
Thread class, its methods, and its companion
interface, Runnable.
 Thread encapsulates a thread of execution.
 Since we can’t directly refer to the ethereal
state of a running thread, you will deal with it
through its proxy, the Thread instance that
spawned it.
22
The Thread Class
 The Thread class defines several methods that
help manage threads.
Method Meaning
getName() Obtain a thread’s name.
getPriority() Obtain a thread’s priority.
isAlive() Determine if a thread is still running.
join() Wait for a thread to terminate.
run() Entry point for the thread.
sleep() Suspend a thread for a period of time.
start() Start a thread by calling its run method.
23
The Main Thread
 When a Java program starts up, one thread
begins running immediately.
 This is usually called the main thread of your
program, because it is the one that is executed
when your program begins.
 The main thread is important for two reasons:
It is the thread from which other “child”
threads will be spawned.
Often, it must be the last thread to finish
execution because it performs various
shutdown actions.
24
The Main Thread
 Although the main thread is created
automatically when your program is started, it
can be controlled through a Thread object.
 To do so, you must obtain a reference to it by
calling the method currentThread( ), which is a
public static member of Thread.
 Its general form is shown here:
static Thread currentThread( )
 Example:
CurrentThreadDemo.java
25
Thread Life Cycle
26
Creating Threads in Java
 This can be done in any one of the following
ways:
 By Sub Classing Thread Class
 By Implementing Runnable
MyThread MyClass
Thread
(objects are threads) (objects with run() body)
Thread Runnable
27
Sub Classing Thread
 To create a thread, we need to create a new
class that extends Thread. and then to create
an instance of that class.
 The extending class must override the run( )
method, which is the entry point for the new
thread.
 It must also call start( ) to begin execution of
the new thread.
 Here is the preceding program rewritten to
extend Thread:
28
Sub Classing Thread
ExtendThread.java
29
Implementing Runnable
 Runnable abstracts a unit of executable code.
 We can construct a thread on any object that
implements Runnable.
 To implement Runnable, a class need only
implement a single method called run( ), which is
declared like this:
public void run( )
 Inside run( ), we will define the code that
constitutes the new thread.
 It is important to understand that run( ) can call
other methods, use other classes, and declare
variables, just like the main thread can.
30
Implementing Runnable
 The only difference is that run( ) establishes
the entry point for another, concurrent thread
of execution within your program.
 This thread will end when run( ) returns.
 After we create a class that implements
Runnable, we will instantiate an object of type
Thread from within that class.
 Thread defines several constructors.
 The one that we will use is shown here:
Thread(Runnable threadOb, String
threadName)
31
Implementing Runnable
ThreadDemo.java
32
Can we start a thread twice
 No. After starting a thread, it can never be
started again.
 If we do so, an IllegalThreadStateException is
thrown.
 In such case, thread will run once but for
second time, it will throw exception.
TestThreadTwice.java
33
Can we call run() directly
 Yes
 Each thread starts in a separate call stack.
 Invoking the run() method from main thread,
the run() method goes onto the current call
stack rather than at the beginning of a new call
stack.
TestCallRun.java
34
Creating Multiple Threads
MultiThreadDemo.java
35
isAlive( ) and join( )
 Often we will want the main thread to finish
last.
 We can achieve this by calling sleep() within
main() method, with a long enough delay to
ensure that all child threads terminate prior to
the main thread.
 However, this is not a satisfactory solution,
and also it raises a larger question: how can one
thread know when another thread has ended.
 For this problem, Thread provides a means
using two methods: isAlive() and join().
36
isAlive()
 isAlive() method is used to determine whether
a thread has finished or not.
 This method is defined by Thread, and its
general form is:
final boolean isAlive()
 The isAlive( ) method returns true if the
thread upon which it is called is still running. It
returns false otherwise.
ThreadisAlive.java
37
join()
 While isAlive( ) is occasionally useful, the
method that you will more commonly use to wait
for a thread to finish is called join( ), shown
here:
final void join( ) throws InterruptedException
final void join(long milliseconds)throws
InterruptedException
38
join()
 This method waits until the thread on which it
is called terminates.
 Its name comes from the concept of the calling
thread waiting until the specified thread joins
it.
 Additional forms of join( ) allow you to specify
a maximum amount of time that you want to
wait for the specified thread to terminate.
ThreadJoinDemo.java
39
Thread Priorities
 Thread priorities are used by the thread
scheduler to decide when each thread should
be allowed to run.
 In theory, over a given period of time, higher-
priority threads get more CPU time than lower-
priority threads.
 In practice, the amount of CPU time that a
thread gets often depends on several factors
besides its priority. (For example, how an
operating system implements multitasking can
affect the relative availability of CPU time.)
40
Thread Priorities
 To set a thread’s priority, use the setPriority()
method, which is a member of Thread. This is its
general form:
final void setPriority(int level)
 Here, level specifies the new priority setting for
the calling thread.
 The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.
 Currently, these values are 1 and 10, respectively.
 To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5.
 These priorities are defined as static final
variables within Thread.
Thread Priorities
 We can obtain the current priority setting by
calling the getPriority( ) method of Thread,
shown here:
final int getPriority( )
 Example:
ThreadDemo.java
41
Synchronization
 When two or more threads need access to a
shared resource, they need some way to ensure
that the resource will be used by only one thread
at a time. The process by which this is achieved
is called synchronization.
 Key to synchronization is the concept of the
monitor.
 A monitor is an object that is used as a mutually
exclusive lock.
42
Synchronization
 Only one thread can own a monitor at a given
time.
 When a thread acquires a lock, it is said to have
entered the monitor.
 All other threads attempting to enter the locked
monitor will be suspended until the first thread
exits the monitor.
 These other threads are said to be waiting for
the monitor.
 A thread that owns a monitor can reenter the
same monitor if it so desires.
43
Types of Synchronization
 There are two types of synchronization
 Process Synchronization
 Thread Synchronization
44
Thread Synchronization
There are two types of thread
synchronization:
Mutual Exclusive
• Synchronized method
• Synchronized block
• Static Synchronization
Inter-Thread Communication
• Cooperation
45
Without Synchronization
In the following example, there is no
synchronization, so output is inconsistent.
Let's see the example:
SynchronizationDemo1.java
46
Synchronization Method
If you declare any method as
synchronized, it is known as synchronized
method.
Synchronized method is used to lock an
object for any shared resource.
When a thread invokes a synchronized
method, it automatically acquires the lock
for that object and releases it when the
thread completes its task.
SynchronizationDemo2.java
47
Synchronized Block
 Synchronized block can be used to perform
synchronization on any specific resource of the
method.
 Suppose you have 50 lines of code in your method,
but you want to synchronize only 5 lines, you can use
synchronized block.
 If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
 Synchronized block is used to lock an object for any
shared resource.
 Scope of synchronized block is smaller than the method.
48
Synchronized Block
 Syntax:
synchronized (object reference expression) {
//code block
}
 Example:
SynchronizedBlockDemo.java
49
Static Synchronization
 If you make any static method as synchronized,
the lock will be on the class not on object.
50
Static Synchronization
 Suppose there are two objects of a shared class(e.g.
Odd) named object1 and object2.
 In case of synchronized method and synchronized
block there cannot be interference between t1 and
t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.
 But there can be interference between t1 and t3 or
t2 and t4 because t1 acquires another lock and t3
acquires another lock.
 We want no interference between t1 and t3 or t2
and t4.
 Static synchronization solves this problem.
51
Static Synchronization
StaticSynchronizationDemo.java
52
Interthread Communication
 The preceding examples unconditionally blocked other
threads from asynchronous access to certain methods.
 This use of the implicit monitors in Java objects is
powerful, but you can achieve a more subtle level of
control through inter-process communication.
 Multithreading replaces event loop programming by
dividing your tasks into discrete, logical units.
 Threads also provide a secondary benefit: they do away
with polling.
 Polling is usually implemented by a loop that is used to
check some condition repeatedly.
 Once the condition is true, appropriate action is taken.
 This wastes CPU time.
53
Interthread Communication
 For example, consider the classic queuing problem,
where one thread is producing some data and
another is consuming it.
 To make the problem more interesting, suppose that
the producer has to wait until the consumer is
finished before it generates more data.
 In a polling system, the consumer would waste many
CPU cycles while it waited for the producer to
produce.
 Once the producer was finished, it would start
polling, wasting more CPU cycles waiting for the
consumer to finish, and so on.
 Clearly, this situation is undesirable.
54
Interthread Communication
 To avoid polling, Java includes an elegant
interprocess communication mechanism via
 wait( ),
 notify( ), and
 notifyAll( ) methods.
 These methods are implemented as final
methods in Object, so all classes have them.
 All three methods can be called only from within
a synchronized context.
55
Interthread Communication
 wait( ) tells the calling thread to give up the
monitor and go to sleep until some other thread
enters the same monitor and calls notify( ) or
notifyAll( ).
 notify( ) wakes up a thread that called wait( ) on
the same object.
 notifyAll( ) wakes up all the threads that called
wait( ) on the same object. One of the threads will
be granted access.
 These methods are declared within Object, as shown
here:
final void wait( ) throws InterruptedException
final void notify( )
final void notify All( )
56
Interthread Communication
 Incorrect implementation of Producer and
Consumer Problem without Interthread
Communication:
PC.java
 Correct implementation with Interthread
Communication:
TCDemo.java
57
ThreadGroup
 Java provides a convenient way to group multiple
threads in a single object.
 In such way, we can suspend, resume or interrupt
group of threads by a single method call.
 A ThreadGroup represents a set of threads. A
thread group can also include the other thread
group.
 The thread group creates a tree in which every
thread group except the initial thread group has a
parent.
 A thread is allowed to access information about
its own thread group, but it cannot access the
information about its thread group's parent
thread group or any other thread groups.
58
ThreadGroup Constructors
public ThreadGroup(String name):
Constructs a new thread group. The parent
of this new group is the thread group of
the currently running thread.
public ThreadGroup(ThreadGroup parent,
String name): Creates a new thread
group. The parent of this new group is the
specified thread group.
59
ThreadGroup Methods
 int activeCount(): This method returns the
number of threads in the group plus any
group for which this thread is parent.
 int activeGroupCount(): This method returns
an estimate of the number of active groups in
this thread group.
 int getMaxPriority(): Returns the maximum
priority setting for the group.
 void setMaxPriority(int priority):Sets the
maximum priority of the invoking group to
priority.
60
ThreadGroup Methods
 ThreadGroup getParent(): Returns null if
the invoking ThreadGroup object has no
parent. Otherwise, it returns the parent of
the invoking object.
 void list(): Displays information about the
group.
 boolean parentOf(ThreadGroup group): This
method tests if this thread group is either
the thread group argument or one of its
ancestor thread groups.
 ThreadGroup getThreadGroup(): This
method returns the ThreadGroup details of
the thread.
61
ThreadGroup Example
ThreadGroupDemo.java
62

More Related Content

What's hot

Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
Ducat India
 
MULTITHREADING CONCEPT
MULTITHREADING CONCEPTMULTITHREADING CONCEPT
MULTITHREADING CONCEPT
RAVI MAURYA
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
kavinilavuG
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
Processes and threads
Processes and threadsProcesses and threads
IPC
IPCIPC
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Correct and efficient synchronization of java thread
Correct and efficient synchronization of java threadCorrect and efficient synchronization of java thread
Correct and efficient synchronization of java thread
outofmemoryerror
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
Adeel Rasheed
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
Kuntal Bhowmick
 
Interprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.SInterprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.S
Hussain Ala'a Alkabi
 
Interprocess communication
Interprocess communicationInterprocess communication
Interprocess communicationSushil Singh
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
Prakhar Maurya
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
Mark Papis
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
IPC
IPCIPC
Concurrency in c#
Concurrency in c#Concurrency in c#
Concurrency in c#
RezaHamidpour
 

What's hot (20)

Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
MULTITHREADING CONCEPT
MULTITHREADING CONCEPTMULTITHREADING CONCEPT
MULTITHREADING CONCEPT
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
IPC
IPCIPC
IPC
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Correct and efficient synchronization of java thread
Correct and efficient synchronization of java threadCorrect and efficient synchronization of java thread
Correct and efficient synchronization of java thread
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Interprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.SInterprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.S
 
Interprocess communication
Interprocess communicationInterprocess communication
Interprocess communication
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
shashank_micro92_00697015
shashank_micro92_00697015shashank_micro92_00697015
shashank_micro92_00697015
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
IPC
IPCIPC
IPC
 
Threads
ThreadsThreads
Threads
 
Concurrency in c#
Concurrency in c#Concurrency in c#
Concurrency in c#
 

Similar to Multithreading

Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
Minal Maniar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
JanmejayaPadhiary2
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
happycocoman
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
BalasundaramSr
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Java Threads
Java ThreadsJava Threads
Java Threads
Hamid Ghorbani
 

Similar to Multithreading (20)

Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
multithreading
multithreadingmultithreading
multithreading
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Java Threads
Java ThreadsJava Threads
Java Threads
 

Recently uploaded

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 

Recently uploaded (20)

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 

Multithreading

  • 2. 2 A Single Threaded Program class ABC { …. public void main(..) { … .. } } begin body end
  • 3. 3 Multithreaded Programming  Java provides built-in support for multithreaded programming.  A multithreaded program contains two or more parts that can run concurrently.  Each part of such a program is called a thread, and each thread defines a separate path of execution.  Thus, multithreading is a specialized form of multitasking.
  • 4. 4 A Multithreaded Program Main Thread Thread A Thread B Thread C start start start Threads may switch or exchange data/results
  • 5. 5 Single and Multithreaded Processes Threads are light-weight processes within a process Single-threaded Process Single instruction stream Multiple instruction stream Multiplethreaded Process Threads of Execution Common Address Space
  • 6. 6 Multitasking  There are two distinct types of multitasking:  process-based and  thread-based  It is important to understand the difference between the two.  For many users, process-based multitasking is the more familiar form.  A process is, in essence, a program that is executing.  Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently.
  • 7. 7 Process-based Multitasking  For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor or visiting a web site.  In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
  • 8. 8 Thread-based Multitasking  In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.  This means that a single program can perform two or more tasks simultaneously.  For instance, a text editor can format text at the same time that it is printing, as long as these two  actions are being performed by two separate threads.  Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the details.
  • 9. 9 Multitasking  Multitasking threads require less overhead than multitasking processes.  Processes are heavyweight tasks that require their own separate address spaces.  Interprocess communication is expensive and limited.  Context switching from one process to another is also costly.
  • 10. 10 Multitasking  Threads, on the other hand, are lighter weight.  They share the same address space and cooperatively share the same heavyweight process.  Interthread communication is inexpensive, and context switching from one thread to the next is lower in cost.  While Java programs make use of process- based multitasking environments, process- based multitasking is not under Java’s control.
  • 11. 11 Multithreaded Server  For Serving Multiple Clients Concurrently Server Threads Server ProcessClient 1 Process Client 2 Process Internet
  • 12. 12 Web/Internet Applications  Serving Many Users Simultaneously Internet Server PC client Local Area Network PDA
  • 13. 13 Multithreaded/Parallel File Copy reader() { - - - - - - - - - - lock(buff[i]); read(src,buff[i]); unlock(buff[i]); - - - - - - - - - - } writer() { - - - - - - - - - - lock(buff[i]); write(src,buff[i]); unlock(buff[i]); - - - - - - - - - - } buff[0] buff[1] Cooperative Parallel Synchronized Threads
  • 14. 14 Levels of Parallelism x LoadCPU Code-Granularity Code Item Large grain (task level) Program Medium grain (control level) Function (thread) Fine grain (data level) Loop (Compiler) Very fine grain (multiple issue) With hardware Task i-l Task i Task i+1 func1 ( ) { .... .... } func2 ( ) { .... .... } func3 ( ) { .... .... } a ( 0 ) =.. b ( 0 ) =.. a ( 1 )=.. b ( 1 )=.. a ( 2 )=.. b ( 2 )=.. + Sockets/ PVM/MPI Threads Compilers
  • 15. 15 What are Threads?  A piece of code that run in concurrent with other threads.  Each thread is a statically ordered sequence of instructions.  Threads are being extensively used express concurrency on both single and multiprocessors machines.  Programming a task having multiple threads of control – Multithreading or Multithreaded Programming.
  • 16. 16 Thread Priorities  Java assigns to each thread a priority that determines how that thread should be treated with respect to the others.  Thread priorities are integers that specify the relative priority of one thread to another.  As an absolute value, a priority is meaningless; a higher-priority thread doesn’t run any faster than a lower-priority thread if it is the only thread running.
  • 17. 17 Context Switch  Instead, a thread’s priority is used to decide when to switch from one running thread to the next.  This is called a context switch. The rules that determine when a context switch takes place are simple:  A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.  A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted-no matter what it is doing-by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.
  • 18. 18 Synchronization  Because multithreading introduces an asynchronous behavior to your programs, there must be a way for you to enforce synchronicity when you need it.  For example, if you want two threads to communicate and share a complicated data structure, such as a linked list, you need some way to ensure that they don’t conflict with each other.  That is, you must prevent one thread from writing data while another thread is in the middle of reading it.
  • 19. 19 Synchronization  For this purpose, Java implements an elegant twist on an age-old model of interprocess synchronization: the monitor.  In Java, there is no class “Monitor”; instead, each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called.  Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object.  This enables you to write very clear and concise multithreaded code, because synchronization support is built into the language.
  • 20. 20 Messaging  After we divide our program into separate threads, we need to define how they will communicate with each other.  When programming with some other languages, we must depend on the operating system to establish communication between threads.  This, of course, adds overhead.  By contrast, Java provides a clean, low-cost way for two or more threads to talk to each other, via calls to predefined methods that all objects have.  Java’s messaging system allows a thread to enter a synchronized method on an object, and then wait there until some other thread explicitly notifies it to come out.
  • 21. 21 The Thread Class and the Runnable Interface  Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable.  Thread encapsulates a thread of execution.  Since we can’t directly refer to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it.
  • 22. 22 The Thread Class  The Thread class defines several methods that help manage threads. Method Meaning getName() Obtain a thread’s name. getPriority() Obtain a thread’s priority. isAlive() Determine if a thread is still running. join() Wait for a thread to terminate. run() Entry point for the thread. sleep() Suspend a thread for a period of time. start() Start a thread by calling its run method.
  • 23. 23 The Main Thread  When a Java program starts up, one thread begins running immediately.  This is usually called the main thread of your program, because it is the one that is executed when your program begins.  The main thread is important for two reasons: It is the thread from which other “child” threads will be spawned. Often, it must be the last thread to finish execution because it performs various shutdown actions.
  • 24. 24 The Main Thread  Although the main thread is created automatically when your program is started, it can be controlled through a Thread object.  To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread.  Its general form is shown here: static Thread currentThread( )  Example: CurrentThreadDemo.java
  • 26. 26 Creating Threads in Java  This can be done in any one of the following ways:  By Sub Classing Thread Class  By Implementing Runnable MyThread MyClass Thread (objects are threads) (objects with run() body) Thread Runnable
  • 27. 27 Sub Classing Thread  To create a thread, we need to create a new class that extends Thread. and then to create an instance of that class.  The extending class must override the run( ) method, which is the entry point for the new thread.  It must also call start( ) to begin execution of the new thread.  Here is the preceding program rewritten to extend Thread:
  • 29. 29 Implementing Runnable  Runnable abstracts a unit of executable code.  We can construct a thread on any object that implements Runnable.  To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( )  Inside run( ), we will define the code that constitutes the new thread.  It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can.
  • 30. 30 Implementing Runnable  The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program.  This thread will end when run( ) returns.  After we create a class that implements Runnable, we will instantiate an object of type Thread from within that class.  Thread defines several constructors.  The one that we will use is shown here: Thread(Runnable threadOb, String threadName)
  • 32. 32 Can we start a thread twice  No. After starting a thread, it can never be started again.  If we do so, an IllegalThreadStateException is thrown.  In such case, thread will run once but for second time, it will throw exception. TestThreadTwice.java
  • 33. 33 Can we call run() directly  Yes  Each thread starts in a separate call stack.  Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack. TestCallRun.java
  • 35. 35 isAlive( ) and join( )  Often we will want the main thread to finish last.  We can achieve this by calling sleep() within main() method, with a long enough delay to ensure that all child threads terminate prior to the main thread.  However, this is not a satisfactory solution, and also it raises a larger question: how can one thread know when another thread has ended.  For this problem, Thread provides a means using two methods: isAlive() and join().
  • 36. 36 isAlive()  isAlive() method is used to determine whether a thread has finished or not.  This method is defined by Thread, and its general form is: final boolean isAlive()  The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise. ThreadisAlive.java
  • 37. 37 join()  While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ), shown here: final void join( ) throws InterruptedException final void join(long milliseconds)throws InterruptedException
  • 38. 38 join()  This method waits until the thread on which it is called terminates.  Its name comes from the concept of the calling thread waiting until the specified thread joins it.  Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. ThreadJoinDemo.java
  • 39. 39 Thread Priorities  Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.  In theory, over a given period of time, higher- priority threads get more CPU time than lower- priority threads.  In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time.)
  • 40. 40 Thread Priorities  To set a thread’s priority, use the setPriority() method, which is a member of Thread. This is its general form: final void setPriority(int level)  Here, level specifies the new priority setting for the calling thread.  The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.  Currently, these values are 1 and 10, respectively.  To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.  These priorities are defined as static final variables within Thread.
  • 41. Thread Priorities  We can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here: final int getPriority( )  Example: ThreadDemo.java 41
  • 42. Synchronization  When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.  Key to synchronization is the concept of the monitor.  A monitor is an object that is used as a mutually exclusive lock. 42
  • 43. Synchronization  Only one thread can own a monitor at a given time.  When a thread acquires a lock, it is said to have entered the monitor.  All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.  These other threads are said to be waiting for the monitor.  A thread that owns a monitor can reenter the same monitor if it so desires. 43
  • 44. Types of Synchronization  There are two types of synchronization  Process Synchronization  Thread Synchronization 44
  • 45. Thread Synchronization There are two types of thread synchronization: Mutual Exclusive • Synchronized method • Synchronized block • Static Synchronization Inter-Thread Communication • Cooperation 45
  • 46. Without Synchronization In the following example, there is no synchronization, so output is inconsistent. Let's see the example: SynchronizationDemo1.java 46
  • 47. Synchronization Method If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task. SynchronizationDemo2.java 47
  • 48. Synchronized Block  Synchronized block can be used to perform synchronization on any specific resource of the method.  Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.  If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.  Synchronized block is used to lock an object for any shared resource.  Scope of synchronized block is smaller than the method. 48
  • 49. Synchronized Block  Syntax: synchronized (object reference expression) { //code block }  Example: SynchronizedBlockDemo.java 49
  • 50. Static Synchronization  If you make any static method as synchronized, the lock will be on the class not on object. 50
  • 51. Static Synchronization  Suppose there are two objects of a shared class(e.g. Odd) named object1 and object2.  In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.  But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.  We want no interference between t1 and t3 or t2 and t4.  Static synchronization solves this problem. 51
  • 53. Interthread Communication  The preceding examples unconditionally blocked other threads from asynchronous access to certain methods.  This use of the implicit monitors in Java objects is powerful, but you can achieve a more subtle level of control through inter-process communication.  Multithreading replaces event loop programming by dividing your tasks into discrete, logical units.  Threads also provide a secondary benefit: they do away with polling.  Polling is usually implemented by a loop that is used to check some condition repeatedly.  Once the condition is true, appropriate action is taken.  This wastes CPU time. 53
  • 54. Interthread Communication  For example, consider the classic queuing problem, where one thread is producing some data and another is consuming it.  To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data.  In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce.  Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on.  Clearly, this situation is undesirable. 54
  • 55. Interthread Communication  To avoid polling, Java includes an elegant interprocess communication mechanism via  wait( ),  notify( ), and  notifyAll( ) methods.  These methods are implemented as final methods in Object, so all classes have them.  All three methods can be called only from within a synchronized context. 55
  • 56. Interthread Communication  wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ) or notifyAll( ).  notify( ) wakes up a thread that called wait( ) on the same object.  notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access.  These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notify All( ) 56
  • 57. Interthread Communication  Incorrect implementation of Producer and Consumer Problem without Interthread Communication: PC.java  Correct implementation with Interthread Communication: TCDemo.java 57
  • 58. ThreadGroup  Java provides a convenient way to group multiple threads in a single object.  In such way, we can suspend, resume or interrupt group of threads by a single method call.  A ThreadGroup represents a set of threads. A thread group can also include the other thread group.  The thread group creates a tree in which every thread group except the initial thread group has a parent.  A thread is allowed to access information about its own thread group, but it cannot access the information about its thread group's parent thread group or any other thread groups. 58
  • 59. ThreadGroup Constructors public ThreadGroup(String name): Constructs a new thread group. The parent of this new group is the thread group of the currently running thread. public ThreadGroup(ThreadGroup parent, String name): Creates a new thread group. The parent of this new group is the specified thread group. 59
  • 60. ThreadGroup Methods  int activeCount(): This method returns the number of threads in the group plus any group for which this thread is parent.  int activeGroupCount(): This method returns an estimate of the number of active groups in this thread group.  int getMaxPriority(): Returns the maximum priority setting for the group.  void setMaxPriority(int priority):Sets the maximum priority of the invoking group to priority. 60
  • 61. ThreadGroup Methods  ThreadGroup getParent(): Returns null if the invoking ThreadGroup object has no parent. Otherwise, it returns the parent of the invoking object.  void list(): Displays information about the group.  boolean parentOf(ThreadGroup group): This method tests if this thread group is either the thread group argument or one of its ancestor thread groups.  ThreadGroup getThreadGroup(): This method returns the ThreadGroup details of the thread. 61