0% found this document useful (0 votes)
25 views

Multithreading and Synchronization

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Multithreading and Synchronization

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

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

• Objective: Create and run three threads:


– The first thread prints the letter a 100 times.
– The second thread prints the letter b 100 times.
– The third thread prints the integers 1 through
100.

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

void start() It is used to start the execution of the thread.


void run() It is used to do an action for a thread.
static void sleep() It sleeps a thread for the specified amount of time.
static Thread currentThread() It returns a reference to the currently executing
thread object.

void join() It waits for a thread to die.


int getPriority() It returns the priority of the thread.
void setPriority() It changes the priority of the thread.
String getName() It returns the name of the thread.
void setName() It changes the name of the thread.
long getId() It returns the id of the thread.
Methods
boolean isAlive() It tests if the thread is alive.
static void yield() It causes the currently executing thread object to
pause and allow other threads to execute
temporarily.

void suspend() It is used to suspend the thread.


void resume() It is used to resume the suspended thread.
void stop() It is used to stop the thread.
void destroy() It is used to destroy the thread group and all of its
subgroups.

boolean isDaemon() It tests if the thread is a daemon thread.


void setDaemon() It marks the thread as daemon or user thread.
void interrupt() It interrupts the thread.
boolean isinterrupted() It tests whether the thread has been interrupted.
static boolean interrupted() It tests whether the current thread has been
interrupted.
Methods
static int activeCount() It returns the number of active threads in the current
thread's thread group.

void checkAccess() It determines if the currently running thread has


permission to modify the thread.

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.

StackTraceElement[] getStackTrace() It returns an array of stack trace elements representing


the stack dump of the thread.

static int enumerate() It is used to copy every active thread's thread group and
its subgroup into the specified array.

Thread.State getState() It is used to return the state of the thread.


ThreadGroup getThreadGroup() It is used to return the thread group to which this thread
belongs
Methods
String toString() It is used to return a string representation of this thread,
including the thread's name, priority, and thread group.

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()

ClassLoader getContextClassLoad It returns the context ClassLoader for the thread.


er()

static getDefaultUncaughtE It returns the default handler invoked when a thread


Thread.UncaughtExc xceptionHandler() abruptly terminates due to an uncaught exception.
eptionHandler

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

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
User Thread vs Daemon Thread
User Thread Daemon Thread

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.

Mainly user threads are designed to do Daemon threads are design as to


some specific task. support the user threads.

Daemon threads are background


User threads are foreground threads.
threads.

User threads are high priority threads. Daemon threads are low priority threads.

Its life independent. Its life depends on user threads.


Thread Priority
• In a Multi threading environment, thread
scheduler assigns processor to a thread based
on priority of thread.
• Whenever we create a thread in Java, it always
has some priority assigned to it.
• int getPriority()
• void setPriority(int newPriority)
Thread Priority
• Each thread is assigned a default priority of the thread that
spawned it.
• The priority of the main thread is
Thread.NORM_PRIORITY .
• Some constants for priorities include
Thread.MIN_PRIORITY : 1

Thread.MAX_PRIORITY : 10

Thread.NORM_PRIORITY : 5

Accepted value of priority for a thread is in range of 1 to 10.


21
• Thread.currentThread().getName()
• Thread.currentThread().getPriority()
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread Running...");
}

public static void main(String[]args)


{
MyThread p1 = new MyThread();
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
p1.start();
System.out.println("P1 thread priority : " + p1.getPriority());
System.out.println("P2 thread priority : " + p2.getPriority());
System.out.println("P3 thread priority : " + p3.getPriority());

}
}
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:

public void run() {


for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex) {
}
}
}

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.

The interrupt() method interrupts a thread in the


following way: If a thread is currently in the Ready or
Running state, its interrupted flag is set; if a thread is
currently blocked, it is awakened and enters the Ready
state, and an java.io.InterruptedException is thrown.

The isInterrupt() method tests whether the thread is


interrupted.
29
Thread Synchronization

A shared resource may be corrupted if it is


accessed simultaneously by multiple threads. For
example, two unsynchronized threads accessing
the same bank account may cause conflict.

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.

You might also like