Multithreading and Thread Synchronization Lecture Note

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

MULTITHREADING AND THREAD

SYNCHRONIZATION

Compiled By G.T 1
Thread Basics

 A thread—sometimes called an execution context or a


lightweight process—is a single sequential flow of control
within a program.
 You use threads to isolate tasks.

 Each thread is a sequential flow of control within the same


program.

 Each sort operation runs independently from the others


but at the same time.

Compiled By G.T 2
cont…

 All programmers are familiar with writing sequential


programs.

 You've probably written a program that displays "Hello


World!" or sorts a list of names or computes a list of prime
numbers.

 These are sequential programs. That is, each has a


beginning, an execution sequence, and an end.
 At any given time during the runtime of the program,
there is a single point of execution.
Compiled By G.T 3
Cont…

 A thread is similar to the sequential programs described


previously.
 A single thread also has a beginning, a sequence, and an
end.
 At any given time during the runtime of the thread, there
is a single point of execution.
 However, a thread itself is not a program; a thread cannot
run on its own. Rather, it runs within a program.
 A thread is a single sequential flow of control within a
program.

Compiled By G.T 4
MULTITHREADING

Compiled By G.T 5
Understanding Multithreading

 All the sample programs you developed in the preceding


chapters have had only a single thread of execution. Each
program proceeded sequentially, one instruction after
another, until it completed its processing and terminated.

 Multithreaded programs are similar to the single-threaded
programs that you have been studying. They differ only in
the fact that they support more than one concurrent thread
of execution-that is, they are able to simultaneously
execute multiple sequences of instructions.

Compiled By G.T 6
Cont…

 Each instruction sequence has its own unique flow of


control that is independent of all others. These
independently executed instruction sequences are known
as threads.

Compiled By G.T 7
logical concurrency and physical
concurrency.

 If your computer has only a single CPU, you might be


wondering how it can execute more than one thread at the
same time.

 In single-processor systems, only a single thread of


execution occurs at a given instant.

 The CPU quickly switches back and forth between several


threads to create the illusion that the threads are executing
at the same time.

Compiled By G.T 8
Cont…

 Single-processor systems support logical concurrency, not


physical concurrency
 Logical concurrency is the characteristic exhibited when
multiple threads execute with separate, independent flows
of control.
 On multiprocessor systems, several threads do, in fact,
execute at the same time, and physical concurrency is
achieved.
 The important feature of multithreaded programs is that
they support logical concurrency, not whether physical
concurrency is actually achieved.
Compiled By G.T 9
Cont…

Compiled By G.T 10
Multiprogramming Vs Multithreading

 Many programming languages support


multiprogramming. Multiprogramming is the logically
concurrent execution of multiple programs.

 For example, a program can request that the operating


system execute programs A, B, and C by having it spawn
a separate process for each program.

 These programs can run in parallel, depending upon the


multiprogramming features supported by the underlying
operating system
Compiled By G.T 11
cont…

 Multithreading differs from multiprogramming in that


multithreading provides concurrency within the context of
a single process and multiprogramming provides
concurrency between processes.
 Threads are not complete processes in and of themselves.
 They are a separate flow of control that occurs within a
process.
 Figure 8.1 illustrates the difference between
multithreading and multiprogramming.

Compiled By G.T 12
Cont…

 Figure 8.1 : Multithreading versus multiprogramming.

Compiled By G.T 13
Cont…

 An executing program is generally associated with a


single process.
 The advantage of multithreading is that concurrency can
be used within a process to provide multiple simultaneous
services to the user.
 Multithreading also requires less processing overhead than
multiprogramming because concurrent threads are able to
share common resources more easily.
 Multiple executing programs tend to duplicate resources
and share data as the result of more time-consuming
interprocess communication.

Compiled By G.T 14
HOW JAVA SUPPORTS
MULTITHREADING

Compiled By G.T 15
Cont…

 Java's multithreading support is centered around the


java.lang.Thread class.
 The Thread class provides the capability to create objects
of class Thread, each with its own separate flow of
control.
 The Thread class encapsulates the data and methods
associated with separate threads of execution and allows
multithreading to be integrated within the object-oriented
framework.

Compiled By G.T 16
Thread life cycle

 A thread life cycle is consisting of the following methods


void start()
 Creates a new thread and makes it runnable
 This method can be called only once

void run()
 The new thread begins its life inside this method

void stop()
 The thread is being terminated

Compiled By G.T 17
Cont…

 yield()
 Causes the currently executing thread object to
temporarily pause and allow other threads to execute
 Allow only threads of the same priority to run

 sleep(int m)/sleep(int m,int n)  


 The thread sleeps for m milliseconds, plus n
nanoseconds

Compiled By G.T 18
approaches to creating threads

Java provides two approaches to creating threads.


1. Subclassing the Thread class and instantiating a new
object of that class
 In the first approach, you create a subclass of class Thread
and override the run() method to provide an entry point
into the thread's execution.
 When you create an instance of your Thread subclass, you
invoke its start() method to cause the thread to execute as
an independent sequence of instructions..

Compiled By G.T 19
Cont…

 The start() method is inherited from the Thread class. It


initializes the Thread object using your operating system's
multithreading capabilities and invokes the run() method.
 Example:-

Compiled By G.T 20
Creating Subclasses of Thread

 In this section, you create your first multithreaded


program by creating a subclass of Thread and then
creating, initializing, and starting two Thread objects from
your class.

 The threads will execute concurrently and display Java is


hot, aromatic, and invigorating. to the console window.

Compiled By G.T 21
class MyThread extends Thread
{
static String message[] =
{ "Java", "is", "hot,", "aromatic,", "and", "invigorating."};
 
public MyThread(String id)
{
super(id);
}
public void run()
{
String name = getName();
for (int i=0;i<message.length;++i) {
randomWait();
System.out.println(name + message[i]);
}}
void randomWait()
{
try {
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
} }}

Compiled By G.T 22
class ThreadTest1
{
public static void main(String args[])
{
MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}
 

Compiled By G.T 23
Cont…

2. Implementing the Runnable interface


 Java's other approach to creating threads does not limit the
location of your Thread objects within the class hierarchy.
In this approach, your class implements the
java.lang.Runnable interface.
 The Runnable interface consists of a single method, the
run() method, which must be overridden by your class.

 The run() method provides an entry point into your


thread's execution. In order to run an object of your class
as an independent thread, you pass it as an argument to a
constructor of class Thread.
Compiled By G.T 24
Cont…(Example)

 In the previous section, you created a multithreaded


program by creating the MyThread subclass of Thread.

 In this section, you create a program with similar


behavior, but you create your threads as objects of the
class MyClass, which is not a subclass of Thread.

 MyClass will implement the Runnable interface and


objects of MyClass will be executed as threads by passing
them as arguments to the Thread constructor.

Compiled By G.T 25
class MyClass implements Runnable
{
static String message[] =
{ "Java", "is", "hot,", "aromatic,", "and", "invigorating."};
String name;
  public MyClass(String id)
{
name = id;
}
public void run()
{
for(int i=0;i<message.length;++i) {
randomWait();
System.out.println(name+message[i]);
}}
  void randomWait()
{
try {
Thread.currentThread().sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}}}

Compiled By G.T 26
class ThreadTest2
{
public static void main(String args[])
{
Thread thread1 = new Thread(new MyClass("thread1: "));
Thread thread2 = new Thread(new MyClass("thread2: "));
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}
 

Compiled By G.T 27
Thread States

Compiled By G.T 28
Cont…

 A thread is created by creating a new object of class


Thread or of one of its subclasses.

 When a thread is first created, it does not exist as an


independently executing set of instructions.

 Instead, it is a template from which an executing thread


will be created. It first executes as a thread when it is
started using the start() method and run via the run()
method.

Compiled By G.T 29
Cont…

 Before a thread is started it is said to be in the new thread


state. After a thread is started, it is in the runnable state.

 When a class is in the runnable state, it may be executing


or temporarily waiting to share processing resources with
other threads.

 A runnable thread enters an extended wait state when one


of its methods is invoked that causes it to drop from the
runnable state into a not runnable state.

Compiled By G.T 30
Cont…

 In the not runnable state, a thread is not just waiting for its
share of processing resources, but is blocked waiting for
the occurrence of an event that will send it back to the
runnable state.

 For example, the sleep() method was invoked in the


ThreadTest1 and ThreadTest2 programs to cause a thread
to wait for a short period of time so that the other thread
could execute

Compiled By G.T 31
Cont…

 The sleep() method causes a thread to enter the not


runnable state until the specified time has expired.

 A thread may also enter the not runnable state while it is


waiting for I/O to be completed, or as the result of the
invocation of other methods.
 A thread leaves the not runnable state and returns to the
runnable state when the event that it is waiting for has
occurred.

Compiled By G.T 32
Cont…

 For example, a sleeping thread must wait for its specified


sleep time to occur. A thread that is waiting on I/O must
wait for the I/O operation to be completed.

 A thread may transition from the new thread, runnable, or


not runnable state to the dead state when its stop() method
is invoked or the thread's execution is completed.

 dead state can't be revived and returned to any other state.

Compiled By G.T 33
Thread Priority and
Scheduling
 From an abstract or a logical perspective, multiple threads
execute as concurrent sequences of instructions.

 This may be physically true for multiprocessor systems,


under certain conditions.

 However, in the general case, multiple threads do not


always physically execute at the same time.

 Instead, the threads share execution time with each other


based on the availability of the system's CPU (or CPUs).

Compiled By G.T 34
Cont…

 The approach used to determining which threads should


execute at a given time is referred to as scheduling.

 Scheduling is performed by the Java runtime system. It


schedules threads based on their priority.

 The highest-priority thread that is in the runnable state is


the thread that is run at any given instant.

Compiled By G.T 35
Cont…

 The highest-priority thread continues to run until it enters


the death state, enters the not runnable state, or has its
priority lowered, or when a higher-priority thread
becomes runnable.
 A thread's priority is an integer value between
MIN_PRIORITY and MAX_PRIORITY.

 These constants are defined in the Thread class. In Java


1.0, MIN_PRIORITY is 1 and MAX_PRIORITY is 10

Compiled By G.T 36
Cont…

 A thread's priority is set when it is created. It is set to the


same priority as the thread that created it.

 The default priority of a thread is NORM_PRIORITY and


is equal to 5. The priority of a thread can be changed using
the setPriority() method.

 Java's approach to scheduling is referred to as preemptive


scheduling.

Compiled By G.T 37
Cont…

 When a thread of higher priority becomes runnable, it


preempts threads of lower priority and is immediately
executed in their place.

 If two or more higher-priority threads become runnable,


the Java scheduler alternates between them when
allocating execution time.

Compiled By G.T 38
Synchronization(Concurrency control
techniques)

 There are many situations in which multiple threads must


share access to common objects
 For example, all of the programs in this chapter have
illustrated the effects of multithreading by having multiple
executing threads write to the Java console, a common
shared object.
 Java enables you to coordinate the actions of multiple
threads using synchronized methods and synchronized
statements.

Compiled By G.T 39
Cont…
 Some of the main techniques used to control concurrent
execution of transactions are based on the concept of
locking data items.
 Locks are used as a means of synchronizing the access by
concurrent threads to the different java objects.

Compiled By G.T 40
Cont…

 In Java, every object has a lock


 To obtain the lock, you must synchronize with the object
 The simplest way to use synchronization is by declaring
one or more methods to be synchronized
 When a synchronized method is invoked, the calling thread
attempts to obtain the lock on the object.
 if it cannot obtain the lock, the thread goes to sleep until the lock
becomes available
 Once the lock is obtained, no other thread can obtain the lock until
it is released. ie, the synchronized method terminates
 When a thread is within a synchronized method, it knows that no
other synchronized method can be invoked by any other thread
 Therefore, it is within synchronized methods that critical data is
updated

Compiled By G.T 41
class ThreadSynchronization
{
public static void main(String args[])
{
MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}

Compiled By G.T 42
class MyThread extends Thread
{
static String message[] =
{ "Java", "is", "hot,", "aromatic,", "and", "invigorating."};
public MyThread(String id)
{
super(id);
}
public void run()
{
SynchronizedOutput.displayList(getName(),message);
}
void randomWait()
{
try {
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}}}

Compiled By G.T 43
class SynchronizedOutput
{
public static synchronized void displayList(String
name,String list[])
{
for(int i=0;i<list.length;++i) {
MyThread t = (MyThread) Thread.currentThread();
t.randomWait();
System.out.println(name+list[i]);
}
}
}

Compiled By G.T 44
A Thread's Life

 A Thread continues to execute until one of the following


things happens:
 It returns from its target run() method
 It's interrupted by an uncaught exception
 Its stop() method is called

Compiled By G.T 45
END……

Compiled By G.T 46

You might also like