Multithreading and Synchronization
Multithreading and Synchronization
1
Multithreading
• Multithreading is a Java feature that allows
concurrent execution of two or more parts of
a program for maximum utilization of CPU.
• Each part of such program is called a thread.
• Threads are light-weight processes within a
process.
• Multithreading in Java is a process of
executing multiple threads simultaneously.
Advantages of Java Multithreading
• 1) It doesn't block the user because threads
are independent and you can perform
multiple operations at the same time.
• 2) You can perform many operations
together, so it saves time.
• 3) Threads are independent, so it doesn't
affect other threads if an exception occurs in a
single thread.
Thread
Threads Concept
Multiple
threads on
multiple
CPUs
Multiple
threads
sharing a
single CPU
5
Example:
Create and Launch Threads
6
Methods to create thread in java
• Threads can be created by using two
mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Methods
Modifier and Type Method Description
static boolean holdLock() It returns true if and only if the current thread holds the
monitor lock on the specified object.
static void dumpStack() It is used to print a stack trace of the current thread to
the standard error stream.
static int enumerate() It is used to copy every active thread's thread group and
its subgroup into the specified array.
void notify() It is used to give the notification for only one thread
which is waiting for a particular object.
void notifyAll() It is used to give the notification to all waiting threads of
a particular object.
void setContextClassLoad It sets the context ClassLoader for the Thread.
er()
static void setDefaultUncaughtE It sets the default handler invoked when a thread
xceptionHandler() abruptly terminates due to an uncaught exception.
Life cycle of a Thread (Thread States)
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
Life Cycle
Thread State Diagram
A thread can be in one of five states: New,
Ready, Running, Blocked, or Finished.
14
Thread States
• 1) New
– The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
• 2) Runnable
– The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
• 3) Running
– The thread is in running state if the thread scheduler has selected it.
• 4) Non-Runnable (Blocked)
– This is the state when the thread is still alive, but is currently not eligible
to run.
• 5) Terminated
– A thread is in terminated or dead state when its run() method exits.
Thread creation by extending the Thread
class
• java.lang package
• Thread class
• run() method
• Start() invokes the run() method on the
Thread object
Java Thread Example by extending Thread
class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Java Thread Example by implementing Runnable interface
JVM wait until user threads to finish their The JVM will’t wait for daemon threads
work. It never exit until all user threads to finish their work. The JVM will exit as
finish their work. soon as all user threads finish their work.
JVM will not force to user threads for If all user threads have finished their
terminating, so JVM will wait for user work JVM will force the daemon threads
threads to terminate themselves. to terminate
User threads are created by the Mostly Daemon threads created by the
application. JVM.
User threads are high priority threads. Daemon threads are low priority threads.
Thread.MAX_PRIORITY : 10
Thread.NORM_PRIORITY : 5
}
}
Thread Synchronization
• to control the access of multiple threads to any
shared resource.
• To prevent thread interference.
• To prevent consistency problem.
• Thread Synchronization
Thread Synchronization
• Thread Synchronization
• There are two types of thread synchronization
mutual exclusive and inter-thread communication.
– Mutual Exclusive
– it will keep the threads from interfering with each other
while sharing any resources.
• Synchronized method.
• Synchronized block.
• static synchronization.
– Cooperation (Inter-thread communication in java)
– It is a mechanism in java in which a thread running in the
critical section is paused and another thread is allowed to
enter or lock the same critical section that is executed.
The Static sleep(milliseconds) Method
The sleep(long mills) method puts the thread to sleep for the
specified time in milliseconds to allow other threads to execute:
Every time a number (>= 50) is printed, the thread is put to sleep for
1 millisecond.
27
isAlive(), interrupt(), and isInterrupted()
The isAlive() method is used to find out the state of a
thread. It returns true if a thread is in the Ready, Blocked,
or Running state; it returns false if a thread is new and has
not started or if it is finished.
30
Inter thread communication
• Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running
in its critical section and another thread is
allowed to enter (or lock) in the same critical
section to be executed.
• It is implemented by following methods
of Object class:
• wait()
• notify()
• notifyAll()
Methods
• wait() method
• Causes current thread to release the lock and
wait until either another thread invokes the
notify() method or the notifyAll() method for
this object, or a specified amount of time has
elapsed.
• notify() method
– Wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax:
– public final void notify()
• notifyAll() method
– Wakes up all threads that are waiting on this object's
monitor. Syntax:
– public final void notifyAll()
suspend() method
• The suspend() method of thread class puts the
thread from running to waiting state.
• This method is used if you want to stop the
thread execution and start it again when a
certain event occurs.
• public final void suspend()
Stop() and resume()
• public void stop()
– This method stops a thread completely.
• public void resume()
– This method resumes a thread, which was
suspended using suspend() method.